Log4Net官方文档
1.创建MS SQL Server日志表
CREATE TABLE [dbo].[Log] (
[Id] [int] IDENTITY (1, 1) NOT NULL,
[Date] [datetime] NOT NULL,
[Thread] [varchar] (255) NOT NULL,
[Level] [varchar] (50) NOT NULL,
[Logger] [varchar] (255) NOT NULL,
[Message] [varchar] (4000) NOT NULL,
[Exception] [varchar] (2000) NULL
)
2.日志表配置-log4net.config中添加(把参数改成自己的,启用了保存到数据库和csv文件)
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<!-- log4net-将日志写入日志文件_按天滚动日志文件,日志文件最大2048KB 最多个数为-1无限个 -->
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<!-- RollingFileAppender以FileAppender为基础 -->
<File value="Log\" />
<!--<file value="${TMP}\LOGS\" /> tmp为环境变量里的路径值,未配置环境变量地址就生成在temp中,log-file.txt为文件名 -->
<param name="AppendToFile" value="true" />
<!-- 指定是追加到还是覆盖掉已有的日志文件 -->
<!--<lockingModel type="log4net.Appender.FileAppender+InterProcessLock" />-->
<param name="lockingModel" type="log4net.Appender.FileAppender+MinimalLock" />
<!-- 启用最小锁定格式以允许多个进程可以写入同一个文件-->
<param name="RollingStyle" value="Composite" />
<!--按照何种方式产生多个日志文件(指明文件名是变动的,日期[Date],文件大小[Size],混合[Composite])-->
<StaticLogFileName value="false" />
<DatePattern value="yyyy\\MM\\dd\\CSV_yyyy-MM-dd'.csv'" />
<MaxSizeRollBackups value="-1" />
<!-- 最多个数为-1无限个-->
<MaximumFileSize value="2MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n=========
%n【日志级别】,【记录时间】,【线程ID】,【出错文件】,【出错行号】,【出错的类】,【属性】,【错误描述】,【错误详情】,
%n %-5level,%date,[%thread],%F,%L,%logger,[%property{NDC}],%message,%newline," />
</layout>
</appender>
log4net-日志表配置
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="0" />
<!--满n条就写到数据库-->
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=172.***.1.***;initial catalog=DBNAME;Persist Security Info=True;User ID=sa;Password=pwd123123" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="@exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<!-- log4net-警告的信息级别区分 -->
<!--<appender name="AspNetTraceAppender" type="log4net.Appender.AspNetTraceAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n==========
%n【日志级别】%-5level
%n【记录时间】%date
%n【线程ID】[%thread]
%n【出错文件】%F
%n【出错行号】%L
%n【出错的类】%logger 属性:[%property{NDC}]
%n【错误描述】%message
%n【错误详情】%newline" />
</layout>
</appender>-->
<!-- log4net-消息缓冲区配置(将日志信息进行缓存,达到10条时把日志输出,只有WARN及更高级别时才会被记录 ) -->
<!--<appender name="BufferingForwardingAppender" type="log4net.Appender.BufferingForwardingAppender" >
<bufferSize value="5"/>
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN"/>
</evaluator>
<appender-ref ref="ConsoleAppender" />
</appender>-->
<!--log4net-ERROR消息打印到控制台_红底白字-->
<!--<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="White" />
<backColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="WARN" />
<foreColor value="Yellow" />
</mapping>
<mapping>
<level value="INFO" />
<foreColor value="White" />
</mapping>
<mapping>
<level value="DEBUG" />
<backColor value="Green" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n==========
%n【日志级别】%-5level
%n【记录时间】%date
%n【线程ID】[%thread]
%n【出错文件】%F
%n【出错行号】%L
%n【出错的类】%logger 属性:[%property{NDC}]
%n【错误描述】%message
%n【错误详情】%newline" />
</layout>
</appender>-->
<!-- log4net-将日志消息定向到控制台错误流 -->
<!--<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<target value="Console.Error" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n==========
%n【日志级别】%-5level
%n【记录时间】%date
%n【线程ID】[%thread]
%n【出错文件】%F
%n【出错行号】%L
%n【出错的类】%logger 属性:[%property{NDC}]
%n【错误描述】%message
%n【错误详情】%newline" />
</layout>
</appender>-->
<!-- log4net-将日志写入本地机器的应用程序事件日志中 -->
<!--<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<applicationName value="MyApp" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n==========
%n【日志级别】%-5level
%n【记录时间】%date
%n【线程ID】[%thread]
%n【出错文件】%F
%n【出错行号】%L
%n【出错的类】%logger 属性:[%property{NDC}]
%n【错误描述】%message
%n【错误详情】%newline" />
</layout>
</appender>-->
<!-- 向指定网络sink发送日志 -->
<!--<appender name="RemotingAppender" type="log4net.Appender.RemotingAppender" >
<sink value="tcp://localhost:8085/LoggingSink" />
<lossy value="true" />
<bufferSize value="95" />
<onlyFixPartialEventData value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="ERROR"/>
</evaluator>
</appender>-->
<!-- 向指定邮箱发送日志 -->
<!--<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender,log4net">
<to value="***@qq.com" />
<from value="[email protected]" />
<username value="[email protected]" />
-->
<!--为客户端授权码-->
<!--
<password value="***********" />
<subject value="B2P主控中心Error警告" />
<smtpHost value="SMTPServer.qq.com" />
<bufferSize value="512" />
-->
<!-- 大小超过512发送一次-->
<!--
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator,log4net">
<threshold value="WARN" />
</evaluator>
<layout type="log4net.Layout.PatternLayout,log4net">
<conversionPattern value="
%n【log4net的HostName】%property{log4net:HostName} ::
%n【日志级别】%-5level
%n【记录时间】%date
%n【线程ID】[%thread]
%n【出错文件】%F
%n【出错行号】%L
%n【出错的类】%logger 属性:%property{NDC}
%n【错误描述】%message
%newlineLogger: %logger%newlineThread: %thread%newlineDate: %date%newlineNDC:
%n【错误详情】%newline%newline" />
</layout>
</appender>-->
<!-- 使用SmtpPickupDir时的配置-->
<!--<appender name="SmtpPickupDirAppender" type="log4net.Appender.SmtpPickupDirAppender">
<to value="[email protected]" />
<from value="[email protected]" />
<subject value="test logging message" />
<pickupDir value="C:\SmtpPickup" />
<bufferSize value="512" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN"/>
</evaluator>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%n==========
%n【日志级别】%-5level
%n【记录时间】%date
%n【线程ID】[%thread]
%n【出错文件】%F
%n【出错行号】%L
%n【出错的类】%logger 属性:[%property{NDC}]
%n【错误描述】%message
%n【错误详情】%newline" />
</layout>
</appender>-->
<root>
<!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->
<level value="all" />
<appender-ref ref="RollingFileAppender" />
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
</configuration>
3.引用log4net的Nuget包
4.添加log4net-helper
(1)第一版
using log4net;
using System;
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
namespace HOST_CONTROL_CENTER.Uril.LogHelper
{
/// <summary>
/// Log4NetHelper
/// </summary>
public class Log4NetHelper
{
#region 执行SQL日志
/// <summary>
/// 普通日志
/// </summary>
/// <param name="message">日志内容</param>
public static void WriteInfo(Type type, string message)
{
ILog log = log4net.LogManager.GetLogger("Info"); // 可以改成type typeof(类)
if (log.IsInfoEnabled)
{
log.Info(message);
}
log = null;
}
/// <summary>
/// 警告日志
/// </summary>
/// <param name="message">警告日志</param>
public static void WriteWarn(Type type, string message)
{
ILog log = log4net.LogManager.GetLogger("Warn");
if (log.IsWarnEnabled)
{
log.Warn(message);
}
log = null;
}
/// <summary>
/// 错误日志
/// </summary>
/// <param name="message">错误日志</param>
public static void WriteError(Type type, string message)
{
ILog log = log4net.LogManager.GetLogger("Error");
if (log.IsInfoEnabled)
{
log.Error(message);
}
log = null;
}
#endregion
public static void TestLog(string aa= "错误")
{
ILog log = log4net.LogManager.GetLogger("Info");
log.Error("Hello World!");
}
}
}
(2)第二版(用这个就够用)
1 using log4net;
2 using System;
3 [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
4 namespace HOST_CONTROL_CENTER.Uril.LogHelper
5 {
6 /// <summary>
7 /// Log4NetHelper
8 /// </summary>
9 public class Log4NetHelper
10 {
11 #region 执行SQL日志
12 /// <summary>
13 /// 普通日志
14 /// </summary>
15 /// <param name="message">日志内容</param>
16 public static void WriteInfo(Type type, string message)
17 {
18 ILog log = log4net.LogManager.GetLogger(type);
19 if (log.IsInfoEnabled)
20 {
21 log.Info(message);
22 }
23 log = null;
24 }
25
26 /// <summary>
27 /// 警告日志
28 /// </summary>
29 /// <param name="message">警告日志</param>
30 public static void WriteWarn(Type type, string message)
31 {
32 ILog log = log4net.LogManager.GetLogger(type);
33 if (log.IsWarnEnabled)
34 {
35 log.Warn(message);
36 }
37 log = null;
38 }
39
40 /// <summary>
41 /// 错误日志
42 /// </summary>
43 /// <param name="message">错误日志</param>
44 public static void WriteError(Type type, string message)
45 {
46 ILog log = log4net.LogManager.GetLogger(type);
47 if (log.IsInfoEnabled)
48 {
49 log.Error(message);
50 }
51 log = null;
52 }
53 #endregion
54
55 public static void TestLog(string aa= "错误")
56 {
57 ILog log = log4net.LogManager.GetLogger("Info");
58 log.Error("Hello World!");
59 }
60 }
61 }
测试例子:
1 private void mitPInfo_Click(object sender, RoutedEventArgs e)
2 {
3 Log4NetHelper.WriteInfo(typeof(MianShow), "信息");
4 }
5
6 private void mitPWarn_Click(object sender, RoutedEventArgs e)
7 {
8 Log4NetHelper.WriteWarn(typeof(MianShow), "警告");
9 }
10
11 private void mitPError_Click(object sender, RoutedEventArgs e)
12 {
13 try{
14 int a = Convert.ToInt32("aa");
15 }
16 catch
17 {
18 Log4NetHelper.WriteError(typeof(MianShow), "a错误");
19 }
20 }
21
22 private void mitPError1_Click(object sender, RoutedEventArgs e)
23 {
24 try
25 {
26 int a = Convert.ToInt32("aa");
27 Log4NetHelper.TestLog("a错误");
28 }
29 catch
30 {
31 Log4NetHelper.TestLog("a错误");
32 }
33 }
结果:
日志文件:
数据库:
(3)其他版本:
1 using log4net;
2 using log4net.Appender;
3 using log4net.Config;
4 using log4net.Repository.Hierarchy;
5 using System;
6 using System.IO;
7
8 //[assembly: XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
9 namespace HOST_CONTROL_CENTER.Uril.LogHelper
10 {
11 public class Log4Helper2
12 {
13 private static ILog ILogger;
14 private static string configFile = "log4net.config";
15
16 static Log4Helper2()
17 {
18 if (File.Exists(Log4NetConfigFile))
19 {
20 if (Environment.OSVersion.Platform == PlatformID.Win32NT)
21 {
22 XmlConfigurator.ConfigureAndWatch(new FileInfo(Log4NetConfigFile));
23 }
24 else
25 {
26 XmlConfigurator.Configure(new FileInfo(Log4NetConfigFile));
27 }
28 }
29 else
30 {
31 BasicConfigurator.Configure();
32 }
33
34 ILogger = GetLogger(typeof(Log4Helper2));
35 }
36
37 #region Abbributes
38 public static string Log4NetConfigFile
39 {
40 get
41 {
42 return Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), configFile);
43
44 }
45 }
46
47 public static ILog GetLogger(System.Type type)
48 {
49 return LogManager.GetLogger(type);
50 }
51 #endregion
52
53 #region 执行SQL日志
54 public static void Info(string message)
55 {
56 ILogger.Info(message);
57 }
58
59 public static void Warn(string message)
60 {
61 ILogger.Warn(message);
62 }
63
64 public static void Error(string message)
65 {
66 ILogger.Error(message);
67 }
68 #endregion
69
70 /// <summary>
71 /// 清理log文件
72 /// </summary>
73 /// <param name="keepDays"></param>
74 public static void ClearOldLogFiles(string keepDays)
75 {
76 int days = 0;
77 int.TryParse(keepDays, out days);
78 if (days <= 0)
79 {
80 return;
81 }
82
83 try
84 {
85 DateTime now = DateTime.Now;
86
87 Hierarchy hierarchy = (Hierarchy)LogManager.GetLoggerRepository();
88 foreach (IAppender appender in hierarchy.Root.Appenders)
89 {
90 if (appender is RollingFileAppender)
91 {
92 string logPath = ((RollingFileAppender)appender).File;
93 DirectoryInfo dir = new DirectoryInfo(logPath.Substring(0, logPath.LastIndexOf("\\")));
94
95 foreach (FileInfo file in dir.GetFiles())
96 {
97 if (file.LastWriteTime < now.AddDays(-days))
98 {
99 file.Delete();
100 }
101 }
102 }
103 }
104 }
105 catch
106 {
107 }
108 }
109 }
110 }
参考文档:https://logging.apache.org/log4net/release/config-examples.html
标签:log4net,log,笔记,public,static,WPF,message,日志 From: https://www.cnblogs.com/qq2806933146xiaobai/p/16805947.html