log4net 按照日期备份日志
配置:
<logger name=
"Log.All"
>
<level value=
"INFO"
/>
<appender-
ref
ref
=
"Log.AllAppender"
/>
</logger>
<appender name=
"Log.AllAppender"
type=
"log4net.Appender.RollingFileAppender,log4net"
>
<param name=
"File"
value=
"..\\Logs\\log.txt"
/>
<param name=
"AppendToFile"
value=
"true"
/>
<param name=
"RollingStyle"
value=
"Date"
/>
<param name=
"DatePattern"
value=
"yyMMdd"
/>
<layout type=
"log4net.Layout.PatternLayout,log4net"
>
<param name=
"ConversionPattern"
value=
"%m%n"
/>
</layout>
</appender>
说明
需求:经过和运维人员确定,我们需要一个记录所有级别信息的日志文件,例如:log.txt,供运维抓取每天的日志信息。
但是:我们不能把所有日志信息一直记录到log.txt,一,log.txt越来越大;二,log.txt包含每天的信息。
策略:根据如上配置,我们会在指定目录下生成log.txt 文件,我们有个模式(yyMMdd)是按天备份,
这样每当第二天第一次日志写入,系统会先把log.txt 备份为log.txt+yyMMdd(log.txt151021),然后清空log.txt。
如此反复:
log.txt 一直记录当天日志信息。
log.txt151021 之前的日志信息
log.txt151020
log.txt151019
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; [assembly: log4net.Config.XmlConfigurator(Watch = true)] namespace UCredit.Abacus.Utility { /// <summary> /// 日志记录 /// </summary> public class Logs { /// <summary> /// 普通日志 /// </summary> //private static ILog LogInfo = LogManager.GetLogger("Log.Info"); /// <summary> /// 错误日志 /// </summary> //private static ILog LogError = LogManager.GetLogger("Log.Error"); /// <summary> /// 全部日志 /// </summary> private static ILog LogAll = LogManager.GetLogger("Log.All"); private static string separator = "^|";//分割符 /// <summary> /// 根据枚举输出日志信息 /// </summary> /// <param name="LogsEnum">枚举(Info;Error)</param> /// <param name="information">输出的信息</param> public static void LogsInfo(LogsEnum logsEnum, string information) { //string logs = "Log." + logsEnum.ToString(); //LogManager.GetLogger(logs).Info(information); LogAll.Info(logsEnum.ToString() + " " + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss") + ":" + information); } /// <summary> /// 根据枚举异步输出日志信息 /// </summary> /// <param name="LogsEnum">枚举(Info;Error)</param> /// <param name="information">输出的信息</param> public static void LogsInfoAsyn(LogsEnum logsEnum, string information) { //string logs = "Log." + logsEnum.ToString(); //Task.Factory.StartNew(() => LogManager.GetLogger(logs).Info(information)); Task.Factory.StartNew(() => LogAll.Info(logsEnum.ToString() + " " + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss") + ":" + information)); } } /// <summary> /// 日志的枚举 /// </summary> public enum LogsEnum { /// <summary> /// 普通日志 /// </summary> Info=0, /// <summary> /// 错误日志 /// </summary> Error } }