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

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名称一致

时间: 2024-08-03 23:33:42

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

log4j的日志文件保存到项目发布目录,log4j文件每天分割按日期命名

自己设置目录,也就是在项目启动时通过System.setProperty来设置,实现ServletContextListener来解决: public class log4jlistener implements ServletContextListener { public static final String log4jdirkey = "log4jdir"; public void contextDestroyed(ServletContextEvent servletcont

基于Log4Net的日志系统

阅读目录 日志系统应具备的特性 Log4Net 配置文件:log4net.config 初始化 输出信息 对Log4Net的封装 log4net.config复杂配置 不管是Web应用程序还是WinForm应用程序,Visual Studio所带的调试功能都是足够强大,足以应付开发中的各种调试需求.但是,对于已经发布的应用,要记录错误.记载运行中的各种状态信息,就需要依靠日志系统了. 回到顶部 日志系统应具备的特性 一个好的日志系统,应该具备以下的特性: 1.运行稳定.因为日志的作用就是要在系统

iOS 打印日志的保存 (一)

当我们真机调试app的时候,作为开发人员的我们可以很方便的通过Xcode的debug area查看相关的打印信息.而测试人员在对app进行测试的时候,一旦出现了crash,这时我们就需要把相关的打印信息保存下来, 以便后面进行查看追踪crash原因.在这里我们可以将打印信息写入沙盒系统中.不多说了,直接上代码. 1 - (void)redirectNSlogToDocumentFolder 2 { 3 if (isatty(STDOUT_FILENO)) 4 { 5 NSLog(@"真机调试,无

(一)使用log4net生成日志文件

1.引入log4net.dll 1.1 Nuget安装 或 http://logging.apache.org/log4net/下载log4net的源代码,编译后把log4net.dll引入项目. 2.配置log4net.config 2.1 在Web.config文件中进行添加configSections的节点 <configSections> <section name="log4net" type="log4net.Config.Log4NetConf

【改进】用Log4net建立日志记录

上一篇随笔中只使用了普通的文件读写来进行日志的写入,正如很多朋友说的,频繁的对文件进行读写会造成很多的问题,代码缺少边界控制和操作控制,没有对资源进行管理,是非常典型的bad code. 然后经过前辈们的提点,今天使用了Log4net进行日志的写入,发现非常的便捷,同时也集成了对于日志的控制,减少因为日志写入而发生的一系列不该有的错误. 网上也有很多教程,在此,结合我的教训,我也厚颜无耻的贴出自己的实现步骤,欢迎前辈们指正!!! app.config配置文件,我是直接写在系统的app.confi

log4net根据日志类型写入到不同的文件中

1 <?xml version="1.0"?> 2 <configuration> 3 <configSections> 4 <!--log4net配置安装--> 5 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> 6 </configSection

log4net 添加自定义日志到数据库

添加操作日志到数据库举例: (一)建立数据库的操作日志表,如下我建立了一个简单的日志表 (二)配置文件中的配置如下 <log4net> <!--错误日志记录数据库--> <logger name="OperateDB"> <level value="INFO"/> <appender-ref ref="AdoNetAppender_OperToSql" /> </logger>

asp.net利用log4net写入日志到SqlServer数据库

asp.net利用log4net写入日志到SqlServer数据库 作者: Kein  来源: 博客园  发布时间: 2010-10-14 07:19  阅读: 6427 次  推荐: 6   原文链接   [收藏] 摘要:Log4net是一个开源的错误日志记录项目,asp.net利用log4net写入日志到SqlServer数据库.下面就我的安装部署log4net到MS sql server的经验与大家分享. asp.net利用log4net写入日志到SqlServer数据库,Log4net是

使用Log4Net发送日志邮件 (转载)

前言 公司前几天重新确立了考核指标,主要是针对我们研发部,而我们的经理要求也高,对我们绩效考核扣分也挺狠的,100分的,出了几个严重bug就变 0分,反正只要被用户发现并且提出来了,就会扣分,没被用户发现自己解决了不追究,还没听说有人写的程序能不出bug,为了能及时的知道出现bug,所以 我在记录错误日志的时候就将错误信息通过邮件发给自己,现在手机微信这么方便,来了邮件就能收到,都是考核惹的祸啊! 正题 log4Net想必很多人都知道,从java的log4j演变而来,开源的,可以到这里下载htt