log4net

log4net.config配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
    </configSections>
    <log4net>
        <root>
            <level value="ALL" />
            <appender-ref ref="LogFileAppender" />
            <!--<appender-ref ref="EventLogAppender" />-->
        </root>
        <!--定义输出到文件-->
        <appender name ="LogFileAppender" type="log4net.Appender.RollingFileAppender">
            <!--定义文件存放位置-->
            <param name="File" value ="App_Data\"/>
            <param name="AppendToFile" value="true" />
            <param name="MaxSizeRollBackups" value="100" />
            <param name="MaxFileSize" value="10240" />
            <param name="StaticLogFileName" value="false" />
            <!--文件名格式-->
            <param name="DatePattern" value="yyyy-MM-dd'.txt'" />
            <param name="RollingStyle" value ="Date" />
            <!--不以独占方式记录日志,仅在记录每个日志的最短时间内锁定,因为部署到服务器上遇到了文件被占用无法下载日志-->
            <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
            <layout type="log4net.Layout.PatternLayout">
                <!--定义输出格式-->
                <!--示例 2018-08-20 12:10:49,348 -线程ID:[21] 日志级别:[INFO ] : [日志信息]-->
                <param name="ConversionPattern" value="%date 线程ID:[%thread] 日志级别:[%-5level] : [%message]%newline"/>
            </layout>
            <!--过滤级别 FATAL > ERROR > WARN > INFO > DEBUG-->
            <filter type="log4net.Filter.LevelRangeFilter">
                <param name="LevelMin" value="DEBUG" />
                <param name="LevelMax" value="FATAL" />
            </filter>
        </appender>
        <!--定义输出到 windows 事件中-->
        <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"></conversionPattern>
            </layout>
        </appender>
    </log4net>
</configuration>

注册

 log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/log4net.config")));

帮助类

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

namespace AZ.EPricing.Utility
{
    public class LogHelper
    {
        private ILog _log4Net = null;
        private const string DEFAULT_LOGGER_NAME = "Logger";
        /// <summary>
        /// Prevents a default instance of the <see cref="LogWriter"/> class from being created.
        /// </summary>
        /// <param name="log4NetInstance">The log4net instance to be used.</param>
        private LogHelper(ILog log4NetInstance)
        {
            _log4Net = log4NetInstance;
        }

        /// <summary>
        /// Gets a logger with the specified configuration name.
        /// </summary>
        /// <param name="configName">Name of the logger in the configuration.</param>
        /// <returns>The logger obtained.</returns>
        /// <exception cref="System.Configuration.ConfigurationException">Thrown when no logger with the specified configuration name was found.</exception>
        public static LogHelper GetLogger(string configName)
        {
            var logger = LogManager.GetLogger(configName);
            if (logger == null)
            {
                throw new ArgumentException(string.Format("No logger configuration named '{0}' was found in the configuration.", configName), "configName");
            }
            return new LogHelper(logger);
        }

        /// <summary>
        /// Gets the default.
        /// </summary>
        public static LogHelper Default
        {
            get
            {
                return GetLogger(DEFAULT_LOGGER_NAME);
            }
        }

        /// <summary>
        /// Writes an information level logging message.
        /// </summary>
        /// <param name="message">The message to be written.</param>
        public void WriteInfo(object message)
        {
            _log4Net.Info(message);
        }

        /// <summary>
        /// Writes a warning level logging message.
        /// </summary>
        /// <param name="message">The message to be written.</param>
        public void WriteWarning(object message)
        {
            _log4Net.Warn(message);
        }

        /// <summary>
        /// Writes a warning level logging message.
        /// </summary>
        /// <param name="message">The message to be written.</param>
        /// <param name="exception">The exception.</param>
        public void WriteWarning(object message, System.Exception exception)
        {
            _log4Net.Warn(message, exception);
        }

        /// <summary>
        /// Writes the error.
        /// </summary>
        /// <param name="message">The message to be written.</param>
        public void WriteError(object message)
        {
            _log4Net.Error(message);
        }

        /// <summary>
        /// Writes the error level logging message..
        /// </summary>
        /// <param name="message">The message to be written.</param>
        /// <param name="exception">The exception.</param>
        public void WriteError(object message, System.Exception exception)
        {
            _log4Net.Error(message, exception);
        }

        /// <summary>
        /// Writes the fatal error level logging message..
        /// </summary>
        /// <param name="message">The message to be written.</param>
        public void WriteFatal(object message)
        {
            _log4Net.Fatal(message);
        }

        /// <summary>
        /// Writes the fatal error level logging message..
        /// </summary>
        /// <param name="message">The message to be written.</param>
        /// <param name="exception">The exception.</param>
        public void WriteFatal(object message, System.Exception exception)
        {
            _log4Net.Fatal(message, exception);
        }

        public void DeleteLog()
        {
            string logDirPath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Log");
            if (!Directory.Exists(logDirPath)) return;
            int days = 30;
            foreach (string filePath in Directory.GetFiles(logDirPath))
            {
                DateTime dt;
                DateTime.TryParse(Path.GetFileNameWithoutExtension(filePath).Replace(@"Log\", "").Replace(".", "-"), out dt);
                if (dt.AddDays(days).CompareTo(DateTime.Now) < 0)
                {
                    File.Delete(filePath);
                }
            }
        }
    }
}

调用

LogHelper.Default.WriteInfo("1000 Success");

 

posted @ 2021-07-07 11:01  萌橙  阅读(85)  评论(0编辑  收藏  举报