一、使用xml配置
①、NuGet
②、添加log4net.appconfig
③、设置生成时复制配置文件(在项目的csproj文件添加节点)
Always
③、后端配置
public ILoggerRepository _log=LogManager.CreateRepository("Logger");XmlConfigurator.Configure(_log, new FileInfo($@"{currentDirectory}\log4net.config"));
二、后端代码配置
①、重写配置项(我这里只写了回滚文件)
public class LoggerHelper { //重写回滚文件 public static RollingFileAppender ConfigRollFile() { string file = $@"{Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)}\Logger\"; RollingFileAppender appender = new RollingFileAppender() { AppendToFile = true, RollingStyle = RollingFileAppender.RollingMode.Composite, File = file, Encoding = Encoding.UTF8, StaticLogFileName = false, DatePattern = "yyyyMMdd\".log\"", MaxSizeRollBackups = 10, MaximumFileSize = "10M", Layout = new log4net.Layout.DynamicPatternLayout( "%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"), }; appender.ActivateOptions(); return appender; } }
②、设置相应配置(我这里覆盖掉回滚文件配置)
ILoggerRepository _log = LogManager.CreateRepository("Logger"); XmlConfigurator.Configure(_log, new FileInfo($@"{currentDirectory}\log4net.config")); RollingFileAppender appender = LoggerHelper.ConfigRollFile(); BasicConfigurator.Configure(_log, appender);
三、获取配置文件属性重新配置
①、修改log4net.config配置文件(其他地方不变)
设置标签
type="log4net.Util.PatternString"、value="%property{FileAddress}/Logger/" ===>log4net 基于log4net.Util.PatternString对属性参数替换
②、后端代码
ILoggerRepository _log = LogManager.CreateRepository("Logger"); log4net.GlobalContext.Properties["FileAddress"] = currentDirectory; XmlConfigurator.Configure(_log, new FileInfo($@"{currentDirectory}\log4net.config"));