大家在使用log4net的时候,常规的用法都是在配置文件里面进行设置。但是配置文件里面的配置项非常多,不利于记忆,所以说我们希望他能直接在代码中设置。
于是,我写了个自定义日志配置的方法,核心的配置对象为RollingFileAppender
,只需要对他进行设置就可以了。
下面给大家展示下,基于使用场景下的日志服务示例。
public class LogService
{
private static readonly ConcurrentDictionary<string, ILog> _loggerContainer = new ConcurrentDictionary<string, ILog>();
public const string Logger_Key_Default = "default";
public const string Logger_Key_Crash = "crash";
static LogService()
{
//初始化默认的日志服务
GetOrAddLogger(Logger_Key_Default, new LoggerConfiguration().SetDefaultValue(Logger_Key_Default));
GetOrAddLogger(Logger_Key_Crash, new LoggerConfiguration().SetDefaultValue(Logger_Key_Crash));
}
/// <summary>
/// 日志统一处理事件
/// </summary>
/// <param name="action"></param>
protected static void DoLog(Action action)
{
SingleThreadPool.Default.Post(() =>
{
action();
});
}
private static ILog GetOrAddLogger(string key, LoggerConfiguration loggerConfiguration)
{
return _loggerContainer.GetOrAdd(key, new Func<string, ILog>((pKey) =>
{
var loggerName = loggerConfiguration.GetFileNameFunc();
Hierarchy repository = (Hierarchy)LogManager.GetRepository();
Logger logger = repository.LoggerFactory.CreateLogger(repository, loggerName);
logger.Hierarchy = repository;
logger.Parent = repository.Root;
logger.Level = loggerConfiguration.LogLevel;
logger.Additivity = false;
logger.AddAppender(GetFileAppender(loggerConfiguration));
logger.Repository.Configured = true;
return new LogImpl(logger);
}));
}
private static ILog GetLoggerFromKey(string key)
{
if (_loggerContainer.ContainsKey(key))
{
return _loggerContainer[key];
}
return default(ILog);
}
private static RollingFileAppender GetFileAppender(LoggerConfiguration logConfiguration)
{
var appender = new RollingFileAppender
{
LockingModel = new FileAppender.MinimalLock(),
Name = "RollingFileAppender",
File = logConfiguration.SavePath,
AppendToFile = true,
MaxSizeRollBackups = logConfiguration.MaxSizeRollBackUps,
MaximumFileSize = logConfiguration.MaximumFileSize,
StaticLogFileName = true,
RollingStyle = RollingFileAppender.RollingMode.Size,
DatePattern = logConfiguration.DatePattern
};
PatternLayout layout = new PatternLayout(logConfiguration.LayoutPattern);
appender.Layout = layout;
layout.ActivateOptions();
appender.ActivateOptions();
return appender;
}
#region 公开事件
public static void Warn(object msg, Exception ex = null)
{
DoLog(() =>
{
GetLoggerFromKey(Logger_Key_Default)?.Warn(msg, ex);
});
}
public static void Info(object msg, Exception ex = null)
{
DoLog(() =>
{
GetLoggerFromKey(Logger_Key_Default)?.Info(msg, ex);
});
}
public static void Debug(object msg, Exception ex = null)
{
DoLog(() =>
{
GetLoggerFromKey(Logger_Key_Default)?.Debug(msg, ex);
});
}
public static void Error(object msg, Exception ex = null)
{
DoLog(() =>
{
GetLoggerFromKey(Logger_Key_Default)?.Error(msg, ex);
});
}
public static void Crash(object msg, Exception ex = null)
{
DoLog(() =>
{
GetLoggerFromKey(Logger_Key_Crash)?.Error(msg, ex);
});
}
#endregion
}
public class LoggerConfiguration
{
public LoggerConfiguration SetDefaultValue(string key)
{
LayoutPattern = "%date% %message%newline";
DatePattern = "yyyyMMdd";
MaxSizeRollBackUps = 20;
MaximumFileSize = "50MB";
LogLevel = Level.All;
GetFileNameFunc = new Func<string>(() =>
{
return $"{key}_{Process.GetCurrentProcess().ProcessName}_{Process.GetCurrentProcess().Id}_{DateTime.Now.ToString("yyyyMMdd")}.log";
});
SavePath = $"{CoreValue.Instance.MizPCTempFilePath}/log/{GetFileNameFunc()}";
return this;
}
public string LayoutPattern { get; set; }
public string DatePattern { get; set; }
public int MaxSizeRollBackUps { get; set; }
public string MaximumFileSize { get; set; }
public Level LogLevel { get; set; }
public string SavePath { get; set; }
public Func<string> GetFileNameFunc { get; set; }
}
这样就可以了。
标签:log4net,自定义,代码,static,ex,Key,msg,Logger,public From: https://blog.csdn.net/qq_22933729/article/details/144145747