问题
I want to have a custom log class, which then injects its properties to nlog Logger. The class should initialize nlog target and config , and then others can use it without the need to know those details.
public interface ILogger
{
void Log(LogEntry entry);
}
public enum LoggingEventType { Debug, Information, Warning, Error, Fatal};
public class LogEntry
{
public readonly LoggingEventType Level;
public readonly string Message;
public readonly Exception Ex;
public LogEntry(LoggingEventType level, string message, Exception exception = null)
{
this.Level = severity;
this.Message = message;
this.Ex = exception;
}
}
public static Main(){
//Should happen in Class MyLogger that implements ILogger
var config = new NLog.Config.LoggingConfiguration();
var logfile = new NLog.Targets.FileTarget("logfile") { FileName
"file.txt" };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
NLog.LogManager.Configuration = config;
LogEntery log = new LogEntry( Error , "Bad stuff" , IOException);
Logger nlog = logger.Error( log.Ex , log.Message);
//How can I inject log level to Nlog class Logger?
}
How can I inject log level to Nlog class Logger?
回答1:
Maybe something like this:
class NLogLogger : ILogger
{
private readonly NLog.Logger _logger;
public NLogLogger(string name)
{
_logger = NLog.LogManager.GetLogger(name);
}
public void Log(LogEntry entry)
{
var nlogLevel = GetNLogLevel(entry.Level);
if (_logger.IsEnabled(nlogLevel))
{
var nlogEvent = NLog.LogEventInfo.Create(nlogLevel, _logger.Name, entry.Message, entry.Ex);
_logger.Log(typeof(NLogLogger), nlogEvent);
}
}
NLog.LogLevel GetNLogLevel(LoggingEventType level)
{
switch (level)
{
case LoggingEventType.Debug: return NLog.LogLevel.Debug;
case LoggingEventType.Information: return NLog.LogLevel.Info;
case LoggingEventType.Warning: return NLog.LogLevel.Warn;
case LoggingEventType.Error: return NLog.LogLevel.Error;
case LoggingEventType.Fatal: return NLog.LogLevel.Fatal;
default: return NLog.LogLevel.Trace;
}
}
}
Sorry for any syntax-errors.
See also: https://github.com/NLog/NLog/wiki/Custom-extension-of-Logger-interface
来源:https://stackoverflow.com/questions/57827089/wrapper-function-for-nlog-assigning-log-level