大家在使用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; }
}
欢迎转载分享,请关注微信公众号,将同步更新博客,方便查看!
本文会经常更新,请阅读原文: https://huchengv5.gitee.io//post/WPF-log4net%E9%80%9A%E8%BF%87%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0%E8%87%AA%E5%AE%9A%E4%B9%89%E9%85%8D%E7%BD%AE.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名胡承(包含链接: https://huchengv5.gitee.io/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 。