C#应用程序日志记录类

在这里插入图片描述
C#应用程序日志记录类_第1张图片
C#应用程序日志记录类_第2张图片
在这里插入图片描述

public class LogHelper
    {
        private const string SError = "Error";
        private const string SDebug = "Debug";
        private const string DefaultName = "Info";

        static LogHelper()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"\log4net_config.xml";
            log4net.Config.XmlConfigurator.Configure(new FileInfo(path));
        }

        public static log4net.ILog GetLog(string logName)
        {
            log4net.ILog log = log4net.LogManager.GetLogger(logName);
            return log;
        }

        public static void Debug(string message)
        {
            var log = log4net.LogManager.GetLogger(SDebug);
            if (log.IsDebugEnabled)
                log.Debug(message);
        }

        public static void Debug(string message, Exception ex)
        {
            var log = log4net.LogManager.GetLogger(SDebug);
            if (log.IsDebugEnabled)
                log.Debug(message, ex);
        }

        public static void Error(string message)
        {
            var log = log4net.LogManager.GetLogger(SError);
            if (log.IsErrorEnabled)
                log.Error(message);
        }

        public static void Error(string message, Exception ex)
        {
            var log = log4net.LogManager.GetLogger(SError);
            if (log.IsErrorEnabled)
            {
                log.Error(message, ex);
                log.Error(ex.Source + "\r\n" + ex.StackTrace + "\r\n" + ex.TargetSite);
            }
        }

        public static void Fatal(string message)
        {
            var log = log4net.LogManager.GetLogger(DefaultName);
            if (log.IsFatalEnabled)
                log.Fatal(message);
        }

        public static void Info(string message)
        {
            log4net.ILog log = log4net.LogManager.GetLogger(DefaultName);
            if (log.IsInfoEnabled)
                log.Info(message);
        }

        public static void Warn(string message)
        {
            var log = log4net.LogManager.GetLogger(DefaultName);
            if (log.IsWarnEnabled)
                log.Warn(message);
        }
}

C#应用程序日志记录类_第3张图片

private void button1_Click(object sender, EventArgs e)
        {
            LogHelper.Debug("debug");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            LogHelper.Error("error");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            LogHelper.Info("info");
        }

在这里插入图片描述
将这个文件放在应用程序文件夹下即可
在这里插入图片描述

你可能感兴趣的:(C#)