动态创建log4net 实例
https://www.cnblogs.com/-dawn/p/8598566.html
根据业务类型,动态的创建日志实例,将日志写到不同目录。常见的配置文件中统一配置,不能满足需求。
-
引用log4net
nuget安装命令: Install-Package log4net -Version 2.0.8
-
日志实例创建类
我这里log实例的相关参数都是直接写死的,你可以根据需要读取配置文件。参数都配有备注,更多参数的含义,网上都可以搜到。
public class GetLog4netInstance
{
private static Dictionary<string, ILog> Logers = new Dictionary<string, ILog>();
/// <summary>
/// 获取log实例
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static ILog GetLogger(string name)
{
if (Logers.ContainsKey(name))
return Logers[name];
else
{
lock (Logers)
{
if (Logers.ContainsKey(name)) return Logers[name];
else
{
var newLoger = CreateLogerInstance(name);
Logers.Add(name, newLoger);
return newLoger;
}
}
}
}
/// <summary>
/// 创建Log实例
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private static ILog CreateLogerInstance(string name)
{
// Pattern Layout
PatternLayout layout = new PatternLayout("%date{yyyy-MM-dd HH:mm:ss} %-5level[%L] %message% %F%newline");
// Level Filter
LevelMatchFilter filter = new LevelMatchFilter();
filter.LevelToMatch = Level.All;
filter.ActivateOptions();
// File Appender
RollingFileAppender appender = new RollingFileAppender();
// 目录
appender.File = $"logs\\{name}\\";
// 立即写入磁盘
appender.ImmediateFlush = true;
// true:追加到文件;false:覆盖文件
appender.AppendToFile = true;
// 新的日期或者文件大小达到上限,新建一个文件
appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
// 文件大小达到上限,新建文件时,文件编号放到文件后缀前面
appender.PreserveLogFileNameExtension = true;
// 时间模式
appender.DatePattern = $"yyyyMMdd'.txt'";
// 最小锁定模型以允许多个进程可以写入同一个文件
appender.LockingModel = new FileAppender.MinimalLock();
appender.Name = $"{name}Appender";
appender.AddFilter(filter);
appender.Layout = layout;
appender.ActivateOptions();
// 文件大小上限
appender.MaximumFileSize = "200MB";
// 设置无限备份=-1 ,最大备份数为30
appender.MaxSizeRollBackups = 30;
appender.StaticLogFileName = false;
//create instance
string repositoryName = $"{name}Repository";
ILoggerRepository repository = LoggerManager.CreateRepository(repositoryName);
BasicConfigurator.Configure(repository, appender);
//After the log instance initialization, we can get the instance from the LogManager by the special log instance name. Then you can start your logging trip.
ILog logger = LogManager.GetLogger(repositoryName, name);
return logger;
}
}
-
调用实例。
创建实例的时候,相关参数直接写死了,所以不需要写配置文件。引用log4net以后,直接调用即可。
static void Main(string[] args)
{
var AccountLoger = GetLog4netInstance.GetLogger("Account");
var BalanceLoger = GetLog4netInstance.GetLogger("Balance");
int i = 0;
while (i < 500)
{
BalanceLoger.Debug(i);
AccountLoger.Debug(i);
i++;
}
Console.WriteLine("结束!");
Console.ReadKey();
}
参考:
["How to programmatically create log instance by Log4Net library"][1]
[1]: https://blogs.perficient.com/delivery/blog/2016/04/20/how-to-programmatically-create-log-instance-by-log4net-library/ "How to programmatically create log instance by Log4Net library"