当需要输出的日志很多的时候,每次修改config都很麻烦,于是想可不可以动态生成。
网上找的案例都是获取单个appender/logger的,此处例子是任意logger,appender相同
log4net的pattern里面关于线程的显示规则是,有线程名用名字,无线程名用线程号。Nlog 可以分别指定
例子如下
1 public static ILog GetLoggerByName(string name)
2 {
3 if (LogManager.Exists(name) == null)
4 {
5
6 // Pattern Layout defined
7 PatternLayout patternLayout = new PatternLayout();
8 patternLayout.ConversionPattern = "%date %thread %level %logger - %message%newline";
9 patternLayout.ActivateOptions();
10
11 // configurating the RollingFileAppender object
12 RollingFileAppender appender = new RollingFileAppender();
13 appender.Name = name;
14 appender.AppendToFile = true;
15 appender.File = $"Log\\{name}.log";
16 appender.StaticLogFileName = true;
17 appender.PreserveLogFileNameExtension = true;
18 appender.LockingModel = new FileAppender.MinimalLock();
19 appender.Layout = patternLayout;
20 appender.MaxSizeRollBackups = 512;
21 appender.MaximumFileSize = "150MB";
22 appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
23 appender.ActivateOptions();
24
25 Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
26
27 var loger = hierarchy.GetLogger(name, hierarchy.LoggerFactory); //!!! 此处写法是重点,不容更改
28 loger.Hierarchy = hierarchy;
29 loger.AddAppender(appender);
30 loger.Level = Level.All;
31
32 BasicConfigurator.Configure();//!!! 此处写法是重点,不容更改
33
34 var appname = Assembly.GetEntryAssembly().GetName().Name;
35 var version= Assembly.GetEntryAssembly().GetName().Version;
36 loger.Log(Level.Info, $"Log name {name} created for Application: {appname} Version: {version}", null);
37 }
38 var log = LogManager.GetLogger(name);
39 return log;
40 }
1 public static void SetMinLogLevel(Level level,string name="")
2 {
3 if(string.IsNullOrEmpty(name))
4 {
5 Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
6 hierarchy.Threshold = level;
7 }
8 else
9 {
10 Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
11 if(hierarchy.Exists(name) is Logger loger)
12 {
13 loger.Level = level;
14 }
15 }
16 }