C# 日志

本篇介绍 log4net 基本使用

一、导包

 

二、配置文件

Log4Net.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="log4net"
          type="log4net.Config.Log4NetConfigurationSectionHandler,&#xD;&#xA;log4net-net-1.0"/>
    </configSections>
    <log4net>
        <appender name="AppLog" type="log4net.Appender.RollingFileAppender">
            <param name="File" value="SysLog/" />
            <param name="AppendToFile" value="true" />
            <param name="MaxSizeRollBackups" value="-1" />
            <!--最小锁定模型以允许多个进程可以写入同一个文件-->
            <param name="lockingModel"  type="log4net.Appender.FileAppender+MinimalLock" />
            <param name="MaximumFileSize" value="10MB" />
            <param name="RollingStyle" value="Size" />
            <param name="DatePattern" value="yyyy-MM-dd" />
            <param name="StaticLogFileName" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%-5p %d [%c] %m%n" />
            </layout>
        </appender>
        <logger name="AppLog">
            <level value="all" />
            <appender-ref ref="AppLog" />
        </logger>
        <root>
            <level value="all" />
        </root>
    </log4net>
</configuration>

 

AppLog.cs
using log4net;
using log4net.Appender;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Log4net
{
    public class AppLog
    {
        private static string filepath = AppDomain.CurrentDomain.BaseDirectory + @"\SysLog\";

        private static readonly log4net.ILog logComm = log4net.LogManager.GetLogger("AppLog");

        static AppLog()
        {
            log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config"));

            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);
            }
        }
        public static readonly object o = new object();
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <param name="isWrite">是否写</param>
        /// <param name="action">写日志的方法</param>
        /// <param name="info">日志文件名,便于分开日志文件</param>
        private static void WriteLog(string msg, bool isWrite, Action<object> action, string info = "")
        {
            if (isWrite)
            {
                lock (o)
                {
                    string filename = $"AppLog_{action.Method.Name}_{info}_{ DateTime.Now.ToString("yyyyMMdd_HH")}.log";
                    var repository = LogManager.GetRepository();

                    #region MyRegion
                    var appenders = repository.GetAppenders();
                    if (appenders.Length > 0)
                    {
                        RollingFileAppender targetApder = null;
                        foreach (var Apder in appenders)
                        {
                            if (Apder.Name == "AppLog")
                            {
                                targetApder = Apder as RollingFileAppender;
                                break;
                            }
                        }
                        if (targetApder.Name == "AppLog")//如果是文件输出类型日志,则更改输出路径
                        {
                            if (targetApder != null)
                            {
                                if (!targetApder.File.Contains(filename))
                                {
                                    targetApder.File = @"SysLog\" + filename;
                                    targetApder.ActivateOptions();
                                }
                            }
                        }
                    }
                    #endregion
                    action(msg);
                    //logComm.Error(msg + "\n");
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <param name="info">日志文件名,便于分开日志文件</param>
        /// <param name="isWrite">是否写入</param>
        public static void WriteError(string msg, string info = "", bool isWrite = true)
        {
            WriteLog(msg, isWrite, logComm.Error, info);
        }
        public static void WriteInfo(string msg, string info = "", bool isWrite = true)
        {
            WriteLog(msg, isWrite, logComm.Info, info);
        }
        public static void WriteWarn(string msg, string info = "", bool isWrite = true)
        {
            WriteLog(msg, isWrite, logComm.Warn, info);
        }
        public static void WriteFatal(string msg, string info = "", bool isWrite = true)
        {
            WriteLog(msg, isWrite, logComm.Fatal, info);
        }
    }
}

 

三、使用

string msg = "用户[张三]:点击了执行了步骤1,发送错误";
AppLog.WriteError(msg,enumLogLevel.WARN);
ShowTCPClientLog(string msg, enumLogLevel logLevel);

 

四、控件展示

/// <summary>
/// 显示日志
/// </summary>
/// <param name="msg">日志内容</param>
/// <param name="logLevel">日志级别</param>
private void ShowTCPClientLog(string msg, enumLogLevel logLevel)
{

    if (!this.rtxt_Recevice.InvokeRequired)
    {
        // 获取当前时间
        string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

        // 根据日志类型选择颜色和符号
        Color color;
        string symbol;
        switch (logLevel)
        {
            case enumLogLevel.INFO:
                symbol = "\u25CF "; // 黑色圆点
                color = Color.Black;
                break;
            case enumLogLevel.DEBUG:
                symbol = "\u25CF "; // 黑色圆点
                color = Color.Black;
                break;
            case enumLogLevel.WARN:
                symbol = "\u26A0 "; // 黄色感叹号
                color = Color.FromArgb(255, 165, 0); // 深橙色
                break;
            case enumLogLevel.ERROR:
                symbol = "\u2718 "; // 红色叉号
                color = Color.Red;
                break;
            case enumLogLevel.FATAL:
                symbol = "\u2718 "; // 红色叉号
                color = Color.Red;
                break;
            default:
                color = Color.Black;
                symbol = "";
                break;
        }

        // 添加新消息
        rtxt_Recevice.SelectionStart = rtxt_Recevice.TextLength;
        rtxt_Recevice.SelectionLength = 0;
        rtxt_Recevice.SelectionColor = color;
        rtxt_Recevice.AppendText(symbol);
        rtxt_Recevice.SelectionColor = rtxt_Recevice.ForeColor; // 恢复默认颜色
        rtxt_Recevice.AppendText($"[{timestamp}] {msg}{Environment.NewLine}");

        // 检查行数是否超过最大行数
        if (rtxt_Recevice.Lines.Length > MaxLines)
        {
            // 删除最早的行
            string[] lines = rtxt_Recevice.Lines;
            string newContent = string.Join(Environment.NewLine, lines.Skip(1).ToArray());
            rtxt_Recevice.Text = newContent;
        }

        // 自动滚动到最后一行
        rtxt_Recevice.ScrollToCaret();
    }
    else
    {
        this.rtxt_Recevice.Invoke(new Action<string, enumLogLevel>(ShowTCPClientLog), msg, logLevel);
    }
}

 

posted @ 2024-07-30 17:16  别动我的猫  阅读(25)  评论(0编辑  收藏  举报