log4net将日志进行分类,保存到不同的目录当中

时间:2022-04-26 02:37:34

1、新建Logs的Class类;代码如下:

  1  public class ApiLogs
  2     {
  3         public static int Log_Level { get; set; }
  4         private static bool initialized = false;
  5         private static readonly ILog log = LogManager.GetLogger("ApiLogs");
  6         static ApiLogs()
  7         {
  8             if (!initialized)
  9             {
 10                 Initialize();
 11                 initialized = true;
 12             }
 13         }
 14         private static void Initialize()
 15         {
 16 
 17             FileInfo fi = new FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
 18             if (fi.Exists)
 19             {
 20                 XmlConfigurator.ConfigureAndWatch(fi);
 21             }
 22             if (!LogManager.GetRepository().Configured)
 23             {
 24                 string filePath = (Path.Combine(Path.GetDirectoryName(new Uri(Assembly.GetCallingAssembly().GetName().CodeBase).LocalPath), "Carpa.config"));
 25                 fi = new FileInfo(filePath);
 26                 if (fi.Exists)
 27                 {
 28                     XmlConfigurator.ConfigureAndWatch(fi);
 29                 }
 30                 else
 31                 {
 32                     Trace.TraceWarning("配置文件 {0} 不存在", fi.FullName);
 33                 }
 34             }
 35         }
 36 
 37 
 38         /// <summary>
 39         /// 调试输出
 40         /// </summary>
 41         /// <param name="message"></param>
 42         public static void Debug(object message)
 43         {
 44             if (Log_Level >= 4)
 45             {
 46                 log.Debug(message);
 47             }
 48         }
 49 
 50         /// <summary>
 51         /// 调试输出
 52         /// </summary>
 53         /// <param name="message"></param>
 54         /// <param name="exception"></param>
 55         public static void Debug(object message, Exception exception)
 56         {
 57             if (Log_Level >= 4)
 58             {
 59                 log.Debug(message, exception);
 60             }
 61         }
 62 
 63         /// <summary>
 64         /// 格式化调试输出
 65         /// </summary>
 66         /// <param name="format"></param>
 67         /// <param name="args"></param>
 68         public static void DebugFormat(string format, params object[] args)
 69         {
 70             if (Log_Level >= 4)
 71             {
 72                 log.DebugFormat(format, args);
 73             }
 74         }
 75 
 76         /// <summary>
 77         /// 信息输出
 78         /// </summary>
 79         /// <param name="message"></param>
 80         public static void Info(object message)
 81         {
 82             if (Log_Level >= 2)
 83             {
 84                 log.Info(message);
 85             }
 86         }
 87 
 88         /// <summary>
 89         /// 信息输出
 90         /// </summary>
 91         /// <param name="message"></param>
 92         /// <param name="exception"></param>
 93         public static void Info(object message, Exception exception)
 94         {
 95             if (Log_Level >= 2)
 96             {
 97                 log.Info(message, exception);
 98             }
 99         }
100 
101         /// <summary>
102         /// 格式化信息输出
103         /// </summary>
104         /// <param name="format"></param>
105         /// <param name="args"></param>
106         public static void InfoFormat(string format, params object[] args)
107         {
108             if (Log_Level >= 2)
109             {
110                 log.InfoFormat(format, args);
111             }
112         }
113 
114         /// <summary>
115         /// 警告输出
116         /// </summary>
117         /// <param name="message"></param>
118         public static void Warn(object message)
119         {
120             if (Log_Level >= 3)
121             {
122                 log.Warn(message);
123             }
124         }
125 
126         /// <summary>
127         /// 警告输出
128         /// </summary>
129         /// <param name="message"></param>
130         /// <param name="exception"></param>
131         public static void Warn(object message, Exception exception)
132         {
133             if (Log_Level >= 3)
134             {
135                 log.Warn(message, exception);
136             }
137         }
138 
139         /// <summary>
140         /// 格式化警告输出
141         /// </summary>
142         /// <param name="format"></param>
143         /// <param name="args"></param>
144         public static void WarnFormat(string format, params object[] args)
145         {
146             if (Log_Level >= 3)
147             {
148                 log.WarnFormat(format, args);
149             }
150         }
151 
152         /// <summary>
153         /// 错误输出
154         /// </summary>
155         /// <param name="message"></param>
156         public static void Error(object message)
157         {
158             if (Log_Level >= 1)
159             {
160                 log.Error(message);
161             }
162         }
163 
164         /// <summary>
165         /// 错误输出
166         /// </summary>
167         /// <param name="message"></param>
168         /// <param name="exception"></param>
169         public static void Error(object message, Exception exception)
170         {
171             if (Log_Level >= 1)
172             {
173                 log.Error(message, exception);
174             }
175         }
176 
177         /// <summary>
178         /// 格式化错误输出
179         /// </summary>
180         /// <param name="format"></param>
181         /// <param name="args"></param>
182         public static void ErrorFormat(string format, params object[] args)
183         {
184             if (Log_Level >= 1)
185             {
186                 log.ErrorFormat(format, args);
187             }
188         }
189 
190         /// <summary>
191         /// 致命输出
192         /// </summary>
193         /// <param name="message"></param>
194         public static void Fatal(object message)
195         {
196             log.Fatal(message);
197         }
198 
199         /// <summary>
200         /// 致命输出
201         /// </summary>
202         /// <param name="message"></param>
203         /// <param name="exception"></param>
204         public static void Fatal(object message, Exception exception)
205         {
206             log.Fatal(message, exception);
207         }
208 
209         /// <summary>
210         /// 格式化致命输出
211         /// </summary>
212         /// <param name="format"></param>
213         /// <param name="args"></param>
214         public static void FatalFormat(string format, params object[] args)
215         {
216             log.FatalFormat(format, args);
217         }
218 
219 
220 
221 
222         /// <summary>
223         /// 是否启用调试输出
224         /// </summary>
225         public static bool IsDebugEnabled
226         {
227             get { return log.IsDebugEnabled; }
228         }
229 
230         /// <summary>
231         /// 是否启用信息输出
232         /// </summary>
233         public static bool IsInfoEnabled
234         {
235             get { return log.IsInfoEnabled; }
236         }
237 
238         /// <summary>
239         /// 是否启用信息输出
240         /// </summary>
241         public static bool IsWarnEnabled
242         {
243             get { return log.IsWarnEnabled; }
244         }
245 
246         /// <summary>
247         /// 是否启用错误输出
248         /// </summary>
249         public static bool IsErrorEnabled
250         {
251             get { return log.IsErrorEnabled; }
252         }
253 
254         /// <summary>
255         /// 是否启用致命输出
256         /// </summary>
257         public static bool IsFatalEnabled
258         {
259             get { return log.IsFatalEnabled; }
260         }
261     }

2、定义Log4net.config配制文件

<?xml version="1.0" encoding="gb2312" ?>
<configuration>
  <configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
  </configSections>

  <log4net>
    <appender name="DebugInfoAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="data\CarpaLog_Info.txt" />
      <appendToFile value="true" />
      <maximumFileSize value="1024KB"/>
      <maxSizeRollBackups value="7"/>
      <CountDirection value="1"/>
      <RollingStyle value="Size"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline%date [%thread] %-5level - %message%newline" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="DEBUG" />
        <levelMax value="INFO" />
      </filter>
    </appender>

    <appender name="WarnErrorFatalAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="data\CarpaLog_Error.txt" />
      <appendToFile value="true" />
      <RollingStyle value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline%date [%thread] %-5level - %message%newline" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="WARN" />
        <levelMax value="FATAL" />
      </filter>
    </appender>

    <appender name="DebugAppender" type="Carpa.Logging.Appender.DebugAppender">
      <layout type="Carpa.Logging.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %type - %message%newline" />
      </layout>
    </appender>

    <appender name="ApiInfoAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="data\ApiLog.txt" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
      <appendToFile value="true" />
      <maximumFileSize value="5MB"/>
      <maxSizeRollBackups value="7"/>
      <CountDirection value="1"/>
      <RollingStyle value="Size"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline%date [%thread] %-5level - %message%newline" />
      </layout>

      <!--<filter type="log4net.Filter.LoggerMatchFilter">
        <loggerToMatch value="ApiLogs" />
      </filter>
      <filter type="log4net.Filter.DenyAllFilter" />-->
      
    </appender>

    <logger name="ApiLogs">
      <level value="ALL" />
      <appender-ref ref="ApiInfoAppender" />
    </logger>
    <logger name="test.Logging.Log">
      <level value="INFO" />
      <appender-ref ref="FileAppender" />
      <appender-ref ref="DebugInfoAppender" />
      <appender-ref ref="WarnErrorFatalAppender" />
    </logger>
  </log4net>
</configuration>

 

核心说明:通过该类logManager.GetLogger("Name")的Name参数来区分,并定义配制文件中logger中name与Getlogger的Name名称一致