C# 实现log日志系统的方法

开发需要,实现一个简单日志系统,废话不多说,直接上代码。
以下基于winform实现。
首先nuget安装Nlog。不会使用nuget自行百度。
 1 using NLog;
 2 
 3 namespace LogDemo
 4 {
 5     public partial class Form1 : Form
 6     {
 7         private static Logger logger = LogManager.GetCurrentClassLogger();
 8         public Form1()
 9         {
10             InitializeComponent();
11             LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration("nlog.config");
12         }
13 
14         private async void btnLogDebug_Click(object sender, EventArgs e)
15         {
16             await Task.Run(() =>
17             {
18                 logger.Debug("Debug message logged.");
19             });
20         }
21 
22         private async void btnLogInfo_Click(object sender, EventArgs e)
23         {
24             await Task.Run(() =>
25             {
26                 logger.Info("Info message logged.");
27             });
28         }
29 
30         private async void btnLogWarning_Click(object sender, EventArgs e)
31         {
32             await Task.Run(() =>
33             {
34                 logger.Warn("Warning message logged.");
35             });
36         }
37 
38         private async void btnLogError_Click(object sender, EventArgs e)
39         {
40             await Task.Run(() =>
41             {
42                 logger.Error("Error message logged.");
43             });
44         }
45 
46         private async void btnLogException_Click(object sender, EventArgs e)
47         {
48             await Task.Run(() =>
49             {
50                 try
51                 {
52                     throw new InvalidOperationException("Demo exception thrown.");
53                 }
54                 catch (Exception ex)
55                 {
56                     logger.Error(ex, "Exception caught and logged.");
57                 }
58             });
59         }
60     }
61 }

其次,配置config。

新建一个Nlog.config文件,放入根目录。

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<targets>
<target xsi:type="File" name="fileTarget" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${level} ${message} ${exception:format=tostring}" />
</targets>

<rules>
<logger name="*" minlevel="Trace" writeTo="fileTarget" />
</rules>
</nlog>

 

 
posted @ 2024-04-10 10:04  上山打母猪  阅读(450)  评论(0)    收藏  举报