C# 打印日志文件

2023-01-10 11:58:46

类库中添加.net4log.dll的引用,然后在类库中新建一个类,加入:

using log4net;
using log4net.Appender;
using System;
using System.IO;
using System.Threading;
using System.Xml;

namespace XingcOpen.ILS.Core.Log
{
    /// <summary>
    /// 日志记录类
    /// </summary>
    /// <typeparam name="T">记录发生所在类</typeparam>
    /// <seealso cref="http://logging.apache.org/log4net"/>
    public sealed class Logger<T>
    {
        /// 日志文件过期时间(单位:天),默认半年=180天
        private static int outdate_days = 60;
        private static readonly ILog log = LogManager.GetLogger(typeof(T));

        static Logger()
        {
            string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LogSettings.config");
            if (File.Exists(configPath))
            {
                log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(configPath));
            }
            #region 删除过期的日期文件
            Thread th = new Thread(() =>
            {
                try
                {
                    DeleteOutdatefiles(log, configPath);
                }
                catch (Exception ex)
                {
                }
            });
            th.IsBackground = true;
            th.Start();
            #endregion
        }

        /// <summary>
        /// 删除过期的日志文件
        /// </summary>
        private static void DeleteOutdatefiles(ILog log, string cfgfile)
        {
            if (log == null ||
                !log.IsInfoEnabled ||
                !log.IsErrorEnabled)
            {
                return;
            }
            try
            {
                XmlDocument xdoc = new XmlDocument();
                xdoc.Load(cfgfile);
                var node = xdoc.SelectSingleNode("log4net");
                //附带属性到log4net.config,只能在根节点设置添加。
                //这个附带属性设置还不能放到其它节点,放到其它节点log4net解析会报错(虽未影响结果,但看着不舒服)
                if (null != node || node.Attributes != null || node.Attributes.Count > 0)
                {
                    outdate_days = 30;
                }
                var apps = log.Logger.Repository.GetAppenders();
                if (apps.Length <= 0)
                {
                    return;
                }
                var now = DateTime.Now;
                foreach (var item in apps)
                {
                    if (item is RollingFileAppender)
                    {
                        RollingFileAppender roll = item as RollingFileAppender;
                        var dir = Path.GetDirectoryName(roll.File);
                        var files = Directory.GetFiles(dir, "*.log");
                        var sample = "20181121-09.log";
                        foreach (var file in files)
                        {
                            var name = Path.GetFileName(file);
                            if (name.Length != sample.Length)
                            {
                                continue;
                            }
                            int year = int.Parse(name.Substring(0, 4));
                            int month = int.Parse(name.Substring(4, 2));
                            int day = int.Parse(name.Substring(6, 2));
                            var date = new DateTime(year, month, day);
                            TimeSpan ts = now - date;
                            if (ts.Days >= outdate_days)
                            {
                                File.Delete(file);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
           
        }


        public static void Error(string message)
        {
            if (log.IsErrorEnabled)
                log.Error(message);
        }

        public static void Error(string message, Exception err)
        {
            if (log.IsErrorEnabled)
                log.Error(message, err);
        }

        public static void Debug(string message)
        {
            if (log.IsDebugEnabled)
                log.Debug(message);
        }

        public static void Info(string message)
        {
            if (log.IsInfoEnabled)
                log.Info(message);
        }
    }
}

然后创建一个LogSettings.config文件,粘贴进如下内容:

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender" >
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="Logs/" />
    <datePattern value="yyyyMMdd-HH'.log'"/>
    <appendToFile value="true" />
    <!--<rollingStyle value="Date" />-->
    <staticLogFileName value="false"/>
    <rollingStyle value="Composite" />
    <maxSizeRollBackups value="35"/>
    <maximumFileSize value="20MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" />
    </layout>
  </appender>
  <root>
    <appender-ref ref="RollingFileAppender" />
    <level value="DEBUG" />
  </root>
  <logger name="NHibernate">
    <level value="WARN" />
  </logger>
</log4net>

将下面这个文件放到你想要打印日志的位置,就可以打印日志拉。

  • 作者:刘梦凡呀
  • 原文链接:https://blog.csdn.net/qq_42782011/article/details/117821071
    更新时间:2023-01-10 11:58:46