log4net学习笔记(一)-WPF


1.创建MS SQL Server日志表

  1. CREATE TABLE [dbo].[Log] (
  2. [Id] [int] IDENTITY (1, 1) NOT NULL,
  3. [Date] [datetime] NOT NULL,
  4. [Thread] [varchar] (255) NOT NULL,
  5. [Level] [varchar] (50) NOT NULL,
  6. [Logger] [varchar] (255) NOT NULL,
  7. [Message] [varchar] (4000) NOT NULL,
  8. [Exception] [varchar] (2000) NULL
  9. )

2.日志表配置-log4net.config中添加(把参数改成自己的,启用了保存到数据库和csv文件)

<?xml version="1.0" encoding="utf-8"?>


























log4net-日志表配置














































































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
{
    /// 
    /// Log4NetHelper
    /// 
    public class Log4NetHelper
    {
        #region 执行SQL日志
        /// 
        /// 普通日志
        /// 
        /// 日志内容
        public static void WriteInfo(Type type, string message)
        {
            ILog log = log4net.LogManager.GetLogger("Info");  // 可以改成type typeof(类)
            if (log.IsInfoEnabled)
            {
                log.Info(message);
            }
            log = null;
        }

        /// 
        /// 警告日志
        /// 
        /// 警告日志
        public static void WriteWarn(Type type, string message)
        {
            ILog log = log4net.LogManager.GetLogger("Warn");
            if (log.IsWarnEnabled)
            {
                log.Warn(message);
            }
            log = null;
        }

        /// 
        /// 错误日志
        /// 
        /// 错误日志
        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     /// 
 7     /// Log4NetHelper
 8     /// 
 9     public class Log4NetHelper
10     {
11         #region 执行SQL日志
12         /// 
13         /// 普通日志
14         /// 
15         /// 日志内容
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         /// 
27         /// 警告日志
28         /// 
29         /// 警告日志
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         /// 
41         /// 错误日志
42         /// 
43         /// 错误日志
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         /// 
 71         /// 清理log文件
 72         /// 
 73         /// 
 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