// Create a new file appender public static RollingFileAppender CreateFileAppender(LoggerConfigurationElement element) { var appender = new RollingFileAppender(); appender.Name = element.LoggerName; appender.File = element.Filename; appender.AppendToFile = true; appender.RollingStyle = RollingFileAppender.RollingMode.Composite; appender.MaximumFileSize = element.MaximumFileSize; appender.MaxSizeRollBackups = element.MaxSizeRollBackups; appender.PreserveLogFileNameExtension = element.PreserveLogFileNameExtension; appender.DatePattern = element.DatePattern; var layout = new PatternLayout(); layout.ConversionPattern = "%message"; layout.ActivateOptions(); var filter = new LoggerMatchFilter(); filter.LoggerToMatch = element.LoggerName; filter.ActivateOptions(); var denyAllFilter = new DenyAllFilter(); denyAllFilter.ActivateOptions(); appender.AddFilter(filter); appender.AddFilter(denyAllFilter); appender.Layout = layout; appender.ActivateOptions(); return(appender); }
private static RollingFileAppender CreateAppender(Level level, PatternLayout layout, string instanceName) { DenyAllFilter filterD = new DenyAllFilter(); filterD.ActivateOptions(); LevelMatchFilter filter = new LevelMatchFilter(); filter.AcceptOnMatch = true; filter.LevelToMatch = level; filter.ActivateOptions(); RollingFileAppender appender = new RollingFileAppender(); appender.File = $"{_mainDirectory}\\logs\\"; appender.ImmediateFlush = true; appender.Encoding = Encoding.UTF8; appender.StaticLogFileName = false; appender.AppendToFile = true; appender.RollingStyle = RollingFileAppender.RollingMode.Date; appender.DatePattern = $"dd.MM.yyyy\\\\'{level.Name}.log'"; appender.LockingModel = new FileAppender.MinimalLock(); appender.Name = $"{instanceName}Appender_{level.Name}"; appender.AddFilter(filter); appender.AddFilter(filterD); appender.Layout = layout; appender.ActivateOptions(); return(appender); }
public static void PrepareLog(string logRoot, string serviceName) { Hierarchy hier = log4net.LogManager.GetRepository() as Hierarchy; string logRootFullName = Path.Combine(logRoot, serviceName, "Starter"); if (null != hier) { RollingFileAppender commonAppender = (RollingFileAppender)hier.GetAppenders().Where(a => a.Name.Equals("CommonAppender")).FirstOrDefault(); if (null != commonAppender) { commonAppender.File = Path.Combine(logRootFullName, "logs.txt"); var filter = new LogExceptionToFileFilter() { ExceptionLogFolder = Path.Combine(logRootFullName, "Exceptions") }; commonAppender.AddFilter(filter); filter.ActivateOptions(); var layout = new SyslogLayout() { StructuredDataPrefix = "CStarterD@" + serviceName }; commonAppender.Layout = layout; layout.ActivateOptions(); commonAppender.ActivateOptions(); } } }
void UseFileLogConfig(Hierarchy repository, LogLevel logLevelMax, LogLevel logLevelMin) { //var ip = JimuHelper.GetLocalIPAddress(); PatternLayout layout = new PatternLayout { ConversionPattern = "%date{yyyy-MM-dd HH:mm:ss.fff} %-5p [%thread] %c %m%n" }; layout.ActivateOptions(); RollingFileAppender roller = new RollingFileAppender { AppendToFile = true, }; var path = string.IsNullOrEmpty(_options.FileLogPath) ? "log" : _options.FileLogPath; roller.File = $@"{path}/"; roller.PreserveLogFileNameExtension = true; roller.StaticLogFileName = false; roller.MaxSizeRollBackups = 0; roller.DatePattern = $@"yyyyMMdd"".log"""; roller.RollingStyle = RollingFileAppender.RollingMode.Date; roller.Layout = layout; roller.MaxFileSize = 10000000; roller.AddFilter(new LevelRangeFilter() { LevelMax = ConvertToLevel(logLevelMax), LevelMin = ConvertToLevel(logLevelMin) }); roller.ActivateOptions(); repository.Root.AddAppender(roller); repository.Configured = true; }
/// <summary> /// Creates the appender. /// </summary> /// <param name="name">The name.</param> /// <param name="file">The file.</param> /// <param name="logLevel">The log level.</param> /// <returns> /// Returns a <see cref="IAppender" /> representing the appender. /// </returns> protected override FileAppender CreateAppender(string name, string file, LogLevel logLevel) { PatternLayout layout = new PatternLayout("%date{yyyy-MM-dd hh:mm:ss tt} - [%level]: %message%newline%exception"); LevelMatchFilter filter = new LevelMatchFilter(); filter.LevelToMatch = logLevel.ToLevel(); filter.ActivateOptions(); var ext = Path.GetExtension(file); var appender = new RollingFileAppender(); appender.Name = name; appender.File = !string.IsNullOrEmpty(ext) ? file.Replace(ext, "") : file; appender.ImmediateFlush = true; appender.RollingStyle = RollingFileAppender.RollingMode.Date; appender.StaticLogFileName = false; appender.DatePattern = "_yyyy-MM-dd'.log'"; appender.AppendToFile = true; appender.LockingModel = new FileAppender.MinimalLock(); appender.AddFilter(filter); appender.Layout = layout; appender.ActivateOptions(); return(appender); }
private RollingFileAppender CreateAppender(string appenderName, string fileName, ComonLog.LogLevel logLevel) { PatternLayout layout = new PatternLayout(); layout.ConversionPattern = "%d %-5p %m%n"; layout.ActivateOptions(); RollingFileAppender appender = new RollingFileAppender(); appender.Layout = layout; appender.Name = appenderName; appender.File = fileName; appender.RollingStyle = RollingFileAppender.RollingMode.Composite; //appender.Encoding = Encoding.Unicode; appender.AppendToFile = true; appender.MaximumFileSize = "4MB"; appender.MaxSizeRollBackups = 100; appender.DatePattern = "yyyy-MM-dd"; appender.PreserveLogFileNameExtension = true; appender.StaticLogFileName = false; appender.Threshold = FileAppenderHelper.ConvertLogLevel(logLevel); log4net.Filter.LevelRangeFilter levfilter = new log4net.Filter.LevelRangeFilter(); levfilter.LevelMax = appender.Threshold; levfilter.LevelMin = appender.Threshold; levfilter.ActivateOptions(); appender.AddFilter(levfilter); appender.ActivateOptions(); return(appender); }
/// <summary> /// 初始化一个<see cref="Log4NetAdapter"/>类型的新实例 /// </summary>k public Log4NetAdapter() { var configFile = Path.Combine(ConfigPath, FileName); if (File.Exists(configFile)) { log4net.GlobalContext.Properties["LogSite"] = LogSite; XmlConfigurator.ConfigureAndWatch(new FileInfo(configFile)); return; } var appender = new RollingFileAppender { Name = "root", File = $"_logs\\local\\{DateTime.Now:yyyyMM}\\", AppendToFile = true, LockingModel = new FileAppender.MinimalLock(), RollingStyle = RollingFileAppender.RollingMode.Date, DatePattern = "dd\".log\"", StaticLogFileName = false, MaxSizeRollBackups = 100, MaximumFileSize = "2MB", Layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss.fff}] %-5p %c %t %w %n%m%n") //Layout = new PatternLayout("[%d [%t] %-5p %c [%x] - %m%n]") }; appender.ClearFilters(); appender.AddFilter(new LevelRangeFilter { LevelMin = Level.Debug, LevelMax = Level.Fatal }); BasicConfigurator.Configure(appender); appender.ActivateOptions(); }
/// <summary> /// 初始化一个<see cref="Log4NetLoggerAdapter"/>类型的新实例 /// </summary> public Log4NetLoggerAdapter() { const string fileName = "log4net.config"; string configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); if (File.Exists(configFile)) { XmlConfigurator.ConfigureAndWatch(new FileInfo(configFile)); return; } RollingFileAppender appender = new RollingFileAppender { Name = "root", File = "logs\\log_", AppendToFile = true, LockingModel = new FileAppender.MinimalLock(), RollingStyle = RollingFileAppender.RollingMode.Date, DatePattern = "yyyyMMdd-HH\".log\"", StaticLogFileName = false, MaxSizeRollBackups = 10, Layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss.fff}] %-5p %c.%M %t %w %n%m%n") }; appender.ClearFilters(); appender.AddFilter(new LevelMatchFilter { LevelToMatch = Level.Info }); BasicConfigurator.Configure(appender); appender.ActivateOptions(); }
private Instance() { Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(); PatternLayout patternLayout = new PatternLayout(); patternLayout.ConversionPattern = Settings._Main.pattern; patternLayout.ActivateOptions(); RollingFileAppender roller = new RollingFileAppender(); roller.AppendToFile = false; roller.File = Settings._Main.logFolder + Settings._Main.masterLogName; roller.Layout = patternLayout; roller.MaxSizeRollBackups = 5; roller.MaximumFileSize = Settings._Main.masterSize; roller.RollingStyle = RollingFileAppender.RollingMode.Size; roller.AppendToFile = true; log4net.Filter.LevelRangeFilter filter = new log4net.Filter.LevelRangeFilter(); filter.LevelMin = log4net.Core.Level.Error; filter.ActivateOptions(); roller.AddFilter(filter); roller.ActivateOptions(); hierarchy.Root.AddAppender(roller); hierarchy.Configured = true; }
private static RollingFileAppender InitializeInfoLogger(string logFilePath) { var infoPatternLayout = new PatternLayout { ConversionPattern = "%date %logger %level - %message%newline", }; infoPatternLayout.ActivateOptions(); var filter = new LevelRangeFilter { LevelMin = Level.Debug, LevelMax = Level.Info, }; filter.ActivateOptions(); var infofileAppender = new RollingFileAppender { AppendToFile = true, File = logFilePath, Layout = infoPatternLayout, LockingModel = new FileAppender.MinimalLock(), MaximumFileSize = "10MB", RollingStyle = RollingFileAppender.RollingMode.Size, StaticLogFileName = false }; infofileAppender.AddFilter(filter); infofileAppender.ActivateOptions(); return(infofileAppender); }
private static ILog CreateUserManagementLogger() { string instanceName = "UserManagement"; PatternLayout layout = new PatternLayout( "% date{ MMM / dd / yyyy HH:mm: ss,fff}[%thread] %-5level %logger %ndc – %message%newline"); LevelMatchFilter filter = new LevelMatchFilter(); filter.LevelToMatch = Level.All; filter.ActivateOptions(); RollingFileAppender appender = new RollingFileAppender(); appender.File = "userManagement.log"; // string.Format("{0}\\{1}", "", "common.log"); appender.ImmediateFlush = true; appender.AppendToFile = true; appender.RollingStyle = RollingFileAppender.RollingMode.Date; appender.DatePattern = "-yyyy - MM - dd"; appender.LockingModel = new FileAppender.MinimalLock(); appender.Name = string.Format("{0}Appender", instanceName); appender.AddFilter(filter); appender.Layout = layout; appender.ActivateOptions(); string repositoryName = string.Format("{0}Repository", instanceName); ILoggerRepository repository = LoggerManager.CreateRepository(repositoryName); string loggerName = string.Format("{0}Logger", instanceName); BasicConfigurator.Configure(repository, appender); return(LogManager.GetLogger(repositoryName, loggerName)); }
/// <summary> /// 初始化一个<see cref="Log4NetLoggerProvider"/>类型的新实例 /// </summary> public Log4NetLoggerProvider(string log4NetConfigFile) { string file = log4NetConfigFile ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DefaultLog4NetFileName); Assembly assembly = Assembly.GetEntryAssembly() ?? GetCallingAssemblyFromStartup(); _loggerRepository = LogManager.CreateRepository(assembly, typeof(Hierarchy)); if (File.Exists(file)) { XmlConfigurator.ConfigureAndWatch(_loggerRepository, new FileInfo(file)); return; } RollingFileAppender appender = new RollingFileAppender { Name = "root", File = "log\\log_", AppendToFile = true, LockingModel = new FileAppender.MinimalLock(), RollingStyle = RollingFileAppender.RollingMode.Date, DatePattern = "yyyyMMdd-HH\".log\"", StaticLogFileName = false, MaxSizeRollBackups = 10, Layout = new PatternLayout("[%d{HH:mm:ss.fff}] %-5p %c T%t %n%m%n") }; appender.ClearFilters(); appender.AddFilter(new LevelMatchFilter() { LevelToMatch = Level.Debug }); BasicConfigurator.Configure(_loggerRepository, appender); appender.ActivateOptions(); }
public TracingInterceptor(string filePath) { PatternLayout layout = new PatternLayout("% date{ MMM / dd / yyyy HH:mm: ss,fff} [%thread] %-5level %logger %ndc – %message%newline"); LevelMatchFilter filter = new LevelMatchFilter(); filter.LevelToMatch = Level.All; filter.ActivateOptions(); RollingFileAppender appender = new RollingFileAppender(); appender.File = filePath; appender.ImmediateFlush = true; appender.AppendToFile = true; appender.RollingStyle = RollingFileAppender.RollingMode.Date; appender.DatePattern = "-yyyy - MM - dd"; appender.LockingModel = new FileAppender.MinimalLock(); appender.Name = "MyAppender"; appender.AddFilter(filter); appender.Layout = layout; appender.ActivateOptions(); ILoggerRepository repository = LoggerManager.CreateRepository("MyRepository"); BasicConfigurator.Configure(repository, appender); _logger = LogManager.GetLogger("MyRepository", "MyLogger"); }
private static RollingFileAppender InitializeErrorLogger(string logFilePath) { var errorPatternLayout = new PatternLayout { ConversionPattern = "%date %logger %level - %message%newline%exception%stacktracedetail", IgnoresException = false, }; errorPatternLayout.ActivateOptions(); var filter = new LevelRangeFilter { LevelMin = Level.Warn, LevelMax = Level.Fatal }; filter.ActivateOptions(); var errorFileAppender = new RollingFileAppender { AppendToFile = true, File = logFilePath, LockingModel = new FileAppender.MinimalLock(), Layout = errorPatternLayout, MaximumFileSize = "10MB", RollingStyle = RollingFileAppender.RollingMode.Size, StaticLogFileName = false }; errorFileAppender.AddFilter(filter); errorFileAppender.ActivateOptions(); return(errorFileAppender); }
/// <summary> /// 初始化一个<see cref="Log4NetAdapter"/>类型的新实例 /// </summary>k public Log4NetAdapter() { var configFile = Path.Combine(ConfigPath, FileName); if (File.Exists(configFile)) { XmlConfigurator.ConfigureAndWatch(new FileInfo(configFile)); return; } var appender = new RollingFileAppender { Name = "root", File = "logs\\log_", AppendToFile = true, LockingModel = new FileAppender.MinimalLock(), RollingStyle = RollingFileAppender.RollingMode.Date, DatePattern = "yyyyMMdd-HH\".log\"", StaticLogFileName = false, MaxSizeRollBackups = 10, Layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss.fff}] %-5p %c %t %w %n%m%n") //Layout = new PatternLayout("[%d [%t] %-5p %c [%x] - %m%n]") }; appender.ClearFilters(); appender.AddFilter(new LevelRangeFilter { LevelMin = Level.Debug, LevelMax = Level.Fatal }); BasicConfigurator.Configure(appender); appender.ActivateOptions(); }
/// <summary> /// Warning: this is not tread-safe, so only call this at startup or at a time that you are sure your /// process is not performing any logging! /// </summary> /// <param name="filePath">The path to the log file.</param> /// <param name="sourceLevels">The lowest log level to log.</param> public static void SetLogFilePath(string filePath, SourceLevels sourceLevels) { if (!Path.IsPathRooted(filePath)) { filePath = Path.Combine(ArgusTVLogFolder, filePath); } Level level = Level.Debug; if (_sourceLevels == SourceLevels.Information) { level = Level.Info; } else if (_sourceLevels == SourceLevels.Warning) { level = Level.Warn; } else if (_sourceLevels == SourceLevels.Error) { level = Level.Error; } else if (_sourceLevels == SourceLevels.Critical) { level = Level.Fatal; } _sourceLevels = sourceLevels; log4Hierarchy.Hierarchy hierarchy = (log4Hierarchy.Hierarchy)LogManager.GetAllRepositories().FirstOrDefault(r => r.Name == _argusTV); if (hierarchy == null) { hierarchy = (log4Hierarchy.Hierarchy)LogManager.CreateRepository(_argusTV); } hierarchy.Root.RemoveAllAppenders(); RollingFileAppender roller = new RollingFileAppender(); PatternLayout patternLayout = new PatternLayout(); patternLayout.ConversionPattern = "%date [%-5level][%thread]: %message%newline"; patternLayout.ActivateOptions(); roller.Layout = patternLayout; roller.AppendToFile = true; roller.RollingStyle = RollingFileAppender.RollingMode.Size; roller.MaxSizeRollBackups = 4; roller.MaximumFileSize = "1000KB"; roller.StaticLogFileName = true; roller.File = filePath; roller.ActivateOptions(); roller.AddFilter(new log4net.Filter.LevelRangeFilter() { LevelMin = level, LevelMax = Level.Fatal }); log4net.Config.BasicConfigurator.Configure(hierarchy, roller); log4Hierarchy.Logger coreLogger = hierarchy.GetLogger(_argusTV) as log4Hierarchy.Logger; coreLogger.Level = level; _log = LogManager.GetLogger(hierarchy.Name, _argusTV); }
public static ILog GetLogger(Type type) { var log = LogManager.GetLogger(type); var consoleAppender = new ConsoleAppender { Layout = new PatternLayout(Pattern) }; consoleAppender.ActivateOptions(); var errorFileAppender = new RollingFileAppender { Layout = new PatternLayout(Pattern), File = "error.log", CountDirection = 1, MaxSizeRollBackups = -1 }; errorFileAppender.AddFilter(new LevelRangeFilter { LevelMin = Level.Error, LevelMax = Level.Fatal }); errorFileAppender.ActivateOptions(); ((Logger)log.Logger).AddAppender(consoleAppender); ((Logger)log.Logger).AddAppender(errorFileAppender); var hierarchy = (Hierarchy)LogManager.GetRepository(); hierarchy.Configured = true; return(log); }
private static RollingFileAppender CreateFileAppender(string appName) { PatternLayout layout = new PatternLayout(); layout.ConversionPattern = "%d{yyyy-MM-dd HH:mm:ss.fff} %-5p [%C{1}] %m%n"; layout.ActivateOptions(); RollingFileAppender appender = new RollingFileAppender(); string path = ConfiguraionProvider.LogPath; string fileSizeInMb = ConfiguraionProvider.FileSizeInMb; appender.AppendToFile = true; appender.File = Path.Combine(Path.Combine(path, appName), string.Format("{0}.log", appName)); appender.ImmediateFlush = true; appender.Layout = layout; appender.MaximumFileSize = string.Format("{0}MB", fileSizeInMb); appender.MaxSizeRollBackups = 2; appender.RollingStyle = RollingFileAppender.RollingMode.Size; appender.StaticLogFileName = true; appender.LockingModel = new FileAppender.MinimalLock(); LevelRangeFilter levelFilter = new LevelRangeFilter(); levelFilter.LevelMin = Level.Info; levelFilter.LevelMax = Level.Fatal; appender.ErrorHandler = new EventLogErrorHandler(); appender.AddFilter(levelFilter); appender.ActivateOptions(); return(appender); }
static void PrepareLogger(string serviceName) { Hierarchy hier = log4net.LogManager.GetRepository() as Hierarchy; string logRootFullName = Path.Combine(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory.TrimEnd(new char[] { '\\' })).FullName, "logs", "CStarter"); if (null != hier) { RollingFileAppender commonAppender = (RollingFileAppender)hier.GetAppenders().Where(a => a.Name.Equals("CommonAppender")).FirstOrDefault(); if (null != commonAppender) { commonAppender.File = Path.Combine(logRootFullName, "Common", "logs.txt"); var filter = new LogExceptionToFileFilter() { ExceptionLogFolder = Path.Combine(logRootFullName, "Common", "Exceptions") }; commonAppender.AddFilter(filter); filter.ActivateOptions(); var layout = new SyslogLayout() { StructuredDataPrefix = "CStarter@" + serviceName }; commonAppender.Layout = layout; layout.ActivateOptions(); commonAppender.ActivateOptions(); } RollingFileAppender starterAppender = (RollingFileAppender)hier.GetAppenders().Where(a => a.Name.Equals("StarterAppender")).FirstOrDefault(); if (null != starterAppender) { starterAppender.File = Path.Combine(logRootFullName, "CStarter", "logs.txt"); var filter = new LogExceptionToFileFilter() { ExceptionLogFolder = Path.Combine(logRootFullName, "CStarter", "Exceptions") }; starterAppender.AddFilter(filter); filter.ActivateOptions(); var layout = new SyslogLayout() { StructuredDataPrefix = "CStarter@" + serviceName }; starterAppender.Layout = layout; layout.ActivateOptions(); starterAppender.ActivateOptions(); } } }
/// <summary> /// Adds a file appender to all current loggers. Only runs one time. /// </summary> /// <param name="outputDirectory">The output directory.</param> private static void set_file_appender(string outputDirectory) { if (!_alreadyConfiguredFileAppender) { _alreadyConfiguredFileAppender = true; var layout = new PatternLayout { ConversionPattern = "%date [%-5level] - %message%newline" }; layout.ActivateOptions(); var app = new RollingFileAppender { Name = "{0}.changes.log.appender".format_with(ApplicationParameters.Name), File = Path.Combine(Path.GetFullPath(outputDirectory), ApplicationParameters.LoggingFile), Layout = layout, AppendToFile = true, RollingStyle = RollingFileAppender.RollingMode.Size, MaxFileSize = 1024 * 1024 * 10, MaxSizeRollBackups = 50, LockingModel = new FileAppender.MinimalLock(), PreserveLogFileNameExtension = true, }; app.ActivateOptions(); var infoOnlyAppender = new RollingFileAppender { Name = _summaryLogAppenderName, File = Path.Combine(Path.GetFullPath(outputDirectory), ApplicationParameters.LoggingSummaryFile), Layout = layout, AppendToFile = true, RollingStyle = RollingFileAppender.RollingMode.Size, MaxFileSize = 1024 * 1024 * 10, MaxSizeRollBackups = 50, LockingModel = new FileAppender.MinimalLock(), PreserveLogFileNameExtension = true, }; infoOnlyAppender.AddFilter(new LevelRangeFilter { LevelMin = Level.Info, LevelMax = Level.Fatal }); infoOnlyAppender.ActivateOptions(); ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetCallingAssembly().UnderlyingType); foreach (ILogger log in logRepository.GetCurrentLoggers()) { var logger = log as Logger; if (logger != null) { logger.AddAppender(app); logger.AddAppender(infoOnlyAppender); } } } }
private static IAppender LoadRollingFileAppender(Log4NetAppenderConfig appenderConfig) { var roller = new RollingFileAppender(); if (!string.IsNullOrWhiteSpace(appenderConfig.ConversionPattern)) { var patternLayout = new PatternLayout { ConversionPattern = appenderConfig.ConversionPattern }; patternLayout.ActivateOptions(); roller.Layout = patternLayout; } roller.File = appenderConfig.File; if (appenderConfig.AppendToFile != null) { roller.AppendToFile = appenderConfig.AppendToFile.Value; } if (appenderConfig.MaxSizeRollBackups != null) { roller.MaxSizeRollBackups = (int)appenderConfig.MaxSizeRollBackups; } if (appenderConfig.StaticLogFileName != null) { roller.StaticLogFileName = (bool)appenderConfig.StaticLogFileName; } if (appenderConfig.RollingStyle != RollingStyles.NotSet) { roller.RollingStyle = GetRollingMode(appenderConfig.RollingStyle); } if (!string.IsNullOrWhiteSpace(appenderConfig.DatePattern)) { roller.DatePattern = appenderConfig.DatePattern; } var rangeFilter = GetLevelRange(appenderConfig); if (rangeFilter != null) { roller.AddFilter(rangeFilter); } roller.ActivateOptions(); return(roller); }
/// <summary> /// 设置日志格式 /// </summary> /// <param name="repositoryName">Repository(版本库)名称</param> /// <param name="level">日志等级</param> static void CreateLogger(string repositoryName, Level level) { ILoggerRepository curRepository = LogManager.GetRepository(repositoryName); //设置日志属性 RollingFileAppender curAppender = new RollingFileAppender() { //日志的名称:版本库+日志登记命名 Name = repositoryName, //日志的保存目录 File = string.Format("log\\{0}\\", repositoryName), //是否静态日志名,静态通过fileAppender.File设置,动态通过日期或者文件大小进行设置 StaticLogFileName = false, //根据日期设置日志文件名 RollingStyle = RollingFileAppender.RollingMode.Composite, //日志文件名的命名规则 DatePattern = string.Format("yyyyMMdd{0}.lo\\g", level), //是否把日志加入到原有日志中。 AppendToFile = true, //每个单独日志文件的最大大小。 MaxFileSize = 50 * 1024 * 1024, //日志可以重写的数量,log,log.1,log.2.... MaxSizeRollBackups = 1000, //选择UTF8编码,确保中文不乱码 Encoding = Encoding.UTF8, LockingModel = new log4net.Appender.FileAppender.MinimalLock() }; //过滤日志等级 LevelRangeFilter filter = new LevelRangeFilter() { LevelMax = level == Level.All ? Level.Fatal : level, LevelMin = level }; curAppender.AddFilter(filter); filter.ActivateOptions(); //设置日志记录的内容 PatternLayout pattenLayout = new PatternLayout() { ConversionPattern = "%date [%thread] %-5level %logger %message%newline" }; curAppender.Layout = pattenLayout; pattenLayout.ActivateOptions(); curAppender.ActivateOptions(); BasicConfigurator.Configure(curRepository, curAppender); }
public RollingFileAppender CreateRollingFileAppender(string filenameAndPath, string rollingfileappender, IFilter filter) { var roller = new RollingFileAppender(); roller.Name = rollingfileappender; roller.AddFilter(filter); roller.Layout = CreatePatternLayout(FILE_LOG_PATTERN); roller.AppendToFile = true; roller.RollingStyle = RollingFileAppender.RollingMode.Size; roller.MaxSizeRollBackups = 4; roller.MaximumFileSize = "10MB"; roller.StaticLogFileName = true; roller.File = filenameAndPath; roller.ActivateOptions(); return(roller); }
private static FileAppender CreateFileAppender(string domain, string rootLogDir, string level, FilterSkeleton filter) { var fileAppender = new RollingFileAppender(); fileAppender.Name = domain + "_" + level + "_FileAppender"; fileAppender.File = System.IO.Path.Combine(rootLogDir, "Log_" + domain + "\\" + level + "\\"); fileAppender.AppendToFile = true; fileAppender.RollingStyle = RollingFileAppender.RollingMode.Date; fileAppender.DatePattern = "yyyy-MM-dd'.log'"; fileAppender.StaticLogFileName = false; fileAppender.Layout = DefaultLayout; fileAppender.AddFilter(filter); fileAppender.ActivateOptions(); return(fileAppender); }
private static IAppender CreateFileAppender(string name, string filePath, IFilter levelFilter) { var layout = new PatternLayout(string.Format(@"Date:%date, Level:%p, Application:{0}, Class:%c, Thread:%t, Message:%m, Exception:%exception%n", _applicationName)); var fileAppender = new RollingFileAppender { Name = name, Layout = layout, File = filePath, RollingStyle = RollingFileAppender.RollingMode.Size, MaxFileSize = 5242880, MaxSizeRollBackups = 3 }; fileAppender.AddFilter(levelFilter); fileAppender.ActivateOptions(); return(fileAppender); }
/// <summary> /// 创建日志实例 /// </summary> /// <param name="name"></param> /// <returns></returns> private static ILog CreateLoggerInstance(string name) { // Pattern Layout PatternLayout layout = new PatternLayout("[%logger][%date]%message\r\n"); // Level Filter LevelMatchFilter filter = new LevelMatchFilter(); filter.LevelToMatch = Level.All; filter.ActivateOptions(); // File Appender RollingFileAppender appender = new RollingFileAppender(); // 目录 appender.File = $"log{Path.AltDirectorySeparatorChar}{name}.log"; // 立即写入磁盘 appender.ImmediateFlush = true; // true:追加到文件;false:覆盖文件 appender.AppendToFile = true; // 新的日期或者文件大小达到上限,新建一个文件 appender.RollingStyle = RollingFileAppender.RollingMode.Once; // 文件大小达到上限,新建文件时,文件编号放到文件后缀前面 appender.PreserveLogFileNameExtension = true; // 最小锁定模型以允许多个进程可以写入同一个文件 appender.LockingModel = new FileAppender.MinimalLock(); appender.Name = $"{name}Appender"; appender.AddFilter(filter); appender.Layout = layout; appender.ActivateOptions(); // 设置无限备份=-1 ,最大备份数为30 appender.MaxSizeRollBackups = 30; appender.StaticLogFileName = true; string repositoryName = $"{name}Repository"; try { LoggerManager.GetRepository(repositoryName); } catch { ILoggerRepository repository = LoggerManager.CreateRepository(repositoryName); BasicConfigurator.Configure(repository, appender); } var logger = LogManager.GetLogger(repositoryName, name); return(logger); }
/// <summary> /// Sets up logging to files /// </summary> private static void SetupLogging() { var hierarchy = (Hierarchy)LogManager.GetRepository(typeof(Program).Assembly); var tracer = new TraceAppender(); var filter = new LevelMatchFilter(); var layout = new PatternLayout("%date{MMM/dd/yyyy HH:mm:ss,fff} [%thread] %-5level %logger %ndc – " + "%message%newline"); tracer.Layout = layout; tracer.ActivateOptions(); hierarchy.Root.AddAppender(tracer); var roller = new RollingFileAppender { File = Path.Combine(Configuration["logs_directory"] ?? "Logs", $"{DateTime.Now.ToString(DateFormat)}.log"), ImmediateFlush = true, AppendToFile = true, StaticLogFileName = true, RollingStyle = RollingFileAppender.RollingMode.Once, LockingModel = new FileAppender.MinimalLock() }; roller.AddFilter(filter); roller.Layout = layout; roller.ActivateOptions(); hierarchy.Root.AddAppender(roller); var consoleAppender = new ConsoleAppender { Layout = layout }; consoleAppender.ActivateOptions(); hierarchy.Root.AddAppender(consoleAppender); Level assumedLevel = hierarchy.LevelMap[Configuration["log_level"] ?? "Info"]; hierarchy.Root.Level = assumedLevel ?? Level.Info; hierarchy.Configured = true; if (assumedLevel is null) { LogManager.GetLogger(typeof(Program)).Error("Unable to set log level. Will use INFO.", null); } }
private RollingFileAppender CreateDailyRollingAppender(string appenderName, string logName, ILayout layout, IFilter filter) { var path = Path.Combine(configuration.LogRootDirectory, logName, logName); var appender = new RollingFileAppender { Name = appenderName, File = path, AppendToFile = true, RollingStyle = RollingFileAppender.RollingMode.Date, StaticLogFileName = false, DatePattern = @"'.'yyyy-MM-dd'.log'", LockingModel = new FileAppender.ExclusiveLock(), Layout = Init(layout) }; appender.AddFilter(Init(filter)); return(Init(appender)); }
private void ActivateAppender() { if (string.IsNullOrEmpty(FolderPath)) { folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Log"); } else { folderPath = FolderPath; } if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } appender.File = Path.Combine(folderPath, InstanceName + "-dev" + DateTime.Now.ToString("ddMMyyyy") + ".log"); appender.AddFilter(filter); appender.ActivateOptions(); }
private AqiRemind() { RollingFileAppender appender = new RollingFileAppender(); appender.File = this.getLogFile(); appender.AppendToFile = true; appender.RollingStyle = RollingFileAppender.RollingMode.Date; appender.StaticLogFileName = true; appender.Layout = new PatternLayout(AqiManage.Setting["AqiRemind.LogLayout"]); LevelRangeFilter filter = new LevelRangeFilter(); filter.LevelMax = Level.Fatal; filter.LevelMin = Level.Debug; appender.AddFilter(filter); appender.ActivateOptions(); BasicConfigurator.Configure(appender); this.log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); }