tafuji / Xamarin-Forms-NLog-Sample

Simple Xamarin.Forms logging sample with NLog
30 stars 14 forks source link

All Logs has "NLogSample" as the "logger" name #5

Open jimmyyentran opened 5 years ago

jimmyyentran commented 5 years ago

How do I change Logger name dynamically so that it reflects the caller class's name?

_logger = LogManager.GetCurrentClassLogger() doesn't seem to work.

${callsite} Layout parameter doesn't seem to work as well. This will resolve to the LoggingService.

jimmyyentran commented 5 years ago

I was able to do this by passing in string parameter to Instance method.

public static ILoggingService Instance(string name)
{
    Lazy<ILoggingService> lazy = new Lazy<ILoggingService>(() => CreateNLogSampleLogging(name), System.Threading.LazyThreadSafetyMode.PublicationOnly);
    return lazy.Value;
}

CreateNLogSampleLogging and LoggingService both takes a string parameter.

Client would call the method like this:

private IpcLogging.ILoggingService _log;
private IpcLogging.ILoggingService Log => _log ?? (_log = IpcLogging.CrossLoggingService.Instance(this.GetType().Name));

or statically:

private static IpcLogging.ILoggingService _log;
private static IpcLogging.ILoggingService Log => _log ?? (_log = IpcLogging.CrossLoggingService.Instance(typeof(MyClass).Name));