Log4Net输出自定义文件日志。

眉间皱痕 提交于 2020-01-08 18:56:28
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Layout;
using log4net.Repository.Hierarchy;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;

namespace NetCoreLog
{
    public static class CustomRollingFileLogger
    {
        private static readonly ConcurrentDictionary<string, ILog> loggerContainer = new ConcurrentDictionary<string, ILog>();

        //默认配置 
        private const int MAX_SIZE_ROLL_BACKUPS = 20;
        private const string LAYOUT_PATTERN = "%n错误时间:%d %n错误级别:%-5p%n错误内容:%m%n";
        private const string DATE_PATTERN = "yyyy-MM-dd";
        private const string MAXIMUM_FILE_SIZE = "200MB";
        private const string LEVEL = "ALL";
        public static ILog GetLogger(string filename = "Log",string category=null)
        {
            category = category ?? DateTime.Now.ToString("yyyy-MM-dd");
            return GetCustomLogger(filename, category);
        }

        public static ILog GetCustomLogger(string loggerName, string category = null, bool additivity = false)
        {
            return loggerContainer.GetOrAdd(loggerName, delegate (string name)
            {
                RollingFileAppender newAppender = GetNewFileApender(loggerName, GetFile(category, loggerName), MAX_SIZE_ROLL_BACKUPS, true, true, MAXIMUM_FILE_SIZE, RollingFileAppender.RollingMode.Composite,
                    DATE_PATTERN, LAYOUT_PATTERN);

                var repository = (Hierarchy)LogManager.GetRepository("NETCoreRepository");
                Logger logger = repository.LoggerFactory.CreateLogger(repository, loggerName);
                logger.Hierarchy = repository;
                logger.Parent = repository.Root;
                logger.Level = GetLoggerLevel(LEVEL);
                logger.Additivity = additivity;
                logger.AddAppender(newAppender);
                logger.Repository.Configured = true;
                return new LogImpl(logger);
            });
        }

        //如果没有指定文件路径则在运行路径下建立 Log\{loggerName}.txt 
        private static string GetFile(string category, string loggerName)
        {
            if (string.IsNullOrEmpty(category))
            {
                return string.Format(@"log\{0}.log", loggerName);
            }
            else
            {
                return string.Format(@"log\{0}\{1}.log", category, loggerName);
            }
        }

        private static Level GetLoggerLevel(string level)
        {
            if (!string.IsNullOrEmpty(level))
            {
                switch (level.ToLower().Trim())
                {
                    case "debug":
                        return Level.Debug;

                    case "info":
                        return Level.Info;

                    case "warn":
                        return Level.Warn;

                    case "error":
                        return Level.Error;

                    case "fatal":
                        return Level.Fatal;
                }
            }
            return Level.Debug;
        }

        private static RollingFileAppender GetNewFileApender(string appenderName, string file, int maxSizeRollBackups, bool appendToFile = true, bool staticLogFileName = false, string maximumFileSize = "2MB", RollingFileAppender.RollingMode rollingMode = RollingFileAppender.RollingMode.Size, string datePattern = "yyyyMMdd\".txt\"", string layoutPattern = "%d [%t] %-5p %c  - %m%n")
        {
            RollingFileAppender appender = new RollingFileAppender
            {
                LockingModel = new FileAppender.MinimalLock(),
                Name = appenderName,
                File = file,
                AppendToFile = appendToFile,
                MaxSizeRollBackups = maxSizeRollBackups,
                MaximumFileSize = maximumFileSize,
                StaticLogFileName = staticLogFileName,
                RollingStyle = rollingMode,
                DatePattern = datePattern
            };
            PatternLayout layout = new PatternLayout(layoutPattern);
            appender.Layout = layout;
            layout.ActivateOptions();
            appender.ActivateOptions();
            return appender;
        }
    }
}
View Code

使用方法

public static void Custom(string fileName,object message)
        {
            var log= CustomRollingFileLogger.GetLogger(fileName);
            log.Info(message);
        }

转载于:https://www.cnblogs.com/LittleFeiHu/p/8651481.html

常规用法:

配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>

  <log4net>
    <!--根配置-->
    <root>
      <!--日志级别:可选值: ERROR > WARN > INFO > DEBUG -->
      <level value="ALL" />
      <appender-ref ref="ErrorLog" />
      <appender-ref ref="WarnLog" />
      <appender-ref ref="InfoLog" />
      <appender-ref ref="DebugLog" />
    </root>
    <!-- 错误 Error.log-->
    <appender name="ErrorLog" type="log4net.Appender.RollingFileAppender">
      <!--目录路径,可以是相对路径或绝对路径-->
      <param name="File" value="./log"/>
      <!--文件名,按日期生成文件夹-->
      <param name="DatePattern" value="/yyyy-MM-dd/&quot;Error.log&quot;"/>
      <!--追加到文件-->
      <appendToFile value="true"/>
      <!--创建日志文件的方式,可选值:Date[日期],文件大小[Size],混合[Composite]-->
      <rollingStyle value="Composite"/>
      <!--写到一个文件-->
      <staticLogFileName value="false"/>
      <!--单个文件大小。单位:KB|MB|GB-->
      <maximumFileSize value="200MB"/>
      <!--最多保留的文件数,设为"-1"则不限-->
      <maxSizeRollBackups value="-1"/>
      <!--日志格式-->
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%n错误时间:%d %n错误级别:%-5p%n错误内容:%m%n"/>
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="ERROR" />
        <param name="LevelMax" value="ERROR" />
      </filter>
    </appender>

    <!-- 警告 Warn.log-->
    <appender name="WarnLog" type="log4net.Appender.RollingFileAppender">
      <!--目录路径,可以是相对路径或绝对路径-->
      <param name="File" value="./log"/>
      <!--文件名,按日期生成文件夹-->
      <param name="DatePattern" value="/yyyy-MM-dd/&quot;Warn.log&quot;"/>
      <!--追加到文件-->
      <appendToFile value="true"/>
      <!--创建日志文件的方式,可选值:Date[日期],文件大小[Size],混合[Composite]-->
      <rollingStyle value="Composite"/>
      <!--写到一个文件-->
      <staticLogFileName value="false"/>
      <!--单个文件大小。单位:KB|MB|GB-->
      <maximumFileSize value="200MB"/>
      <!--最多保留的文件数,设为"-1"则不限-->
      <maxSizeRollBackups value="-1"/>
      <!--日志格式-->
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%n日志时间:%d %n日志级别:%-5p%n日志内容:%m%n"/>
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="WARN" />
        <param name="LevelMax" value="WARN" />
      </filter>
    </appender>

    <!-- 信息 Info.log-->
    <appender name="InfoLog" type="log4net.Appender.RollingFileAppender">
      <!--目录路径,可以是相对路径或绝对路径-->
      <param name="File" value="./log"/>
      <!--文件名,按日期生成文件夹-->
      <param name="DatePattern" value="/yyyy-MM-dd/&quot;Info.log&quot;"/>
      <!--追加到文件-->
      <appendToFile value="true"/>
      <!--创建日志文件的方式,可选值:Date[日期],文件大小[Size],混合[Composite]-->
      <rollingStyle value="Composite"/>
      <!--写到一个文件-->
      <staticLogFileName value="false"/>
      <!--单个文件大小。单位:KB|MB|GB-->
      <maximumFileSize value="200MB"/>
      <!--最多保留的文件数,设为"-1"则不限-->
      <maxSizeRollBackups value="-1"/>
      <!--日志格式-->
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%n日志时间:%d %n日志级别:%-5p%n日志内容:%m%n"/>
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="INFO" />
        <param name="LevelMax" value="INFO" />
      </filter>
    </appender>

    <!-- 调试 Debug.log-->
    <appender name="DebugLog" type="log4net.Appender.RollingFileAppender">
      <!--目录路径,可以是相对路径或绝对路径-->
      <param name="File" value="./log"/>
      <!--文件名,按日期生成文件夹-->
      <param name="DatePattern" value="/yyyy-MM-dd/&quot;Debug.log&quot;"/>
      <!--追加到文件-->
      <appendToFile value="true"/>
      <!--创建日志文件的方式,可选值:Date[日期],文件大小[Size],混合[Composite]-->
      <rollingStyle value="Composite"/>
      <!--写到一个文件-->
      <staticLogFileName value="false"/>
      <!--单个文件大小。单位:KB|MB|GB-->
      <maximumFileSize value="200MB"/>
      <!--最多保留的文件数,设为"-1"则不限-->
      <maxSizeRollBackups value="-1"/>
      <!--日志格式-->
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%n日志时间:%d %n日志级别:%-5p%n日志内容:%m%n"/>
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="DEBUG" />
        <param name="LevelMax" value="DEBUG" />
      </filter>
    </appender>
  </log4net>
</configuration>

使用

using log4net;
using log4net.Config;
using log4net.Core;
using log4net.Repository;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace NetCoreLog
{
    public static class Log4NetHelper
    {
        private static ILog logger;
        static Log4NetHelper()
        {
            ILoggerRepository repository = LogManager.CreateRepository("NETCoreRepository");
            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
            logger = LogManager.GetLogger(repository.Name, "NETCorelog4net");
        }
        public static void Debug(object message)
        {
            logger.Debug(message);
        }
        public static void Error(object message)
        {
            logger.Error(message);
        }
        public static void Info(object message)
        {
            logger.Info(message);
        }
        public static void Warn(object message)
        {
            logger.Warn(message);
        }
        public static void Custom(string fileName,object message)
        {
            var log= CustomRollingFileLogger.GetLogger(fileName);
            log.Info(message);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!