Log的使用

37 篇文章 0 订阅

step1:添加log4net的引用

step2:添加配置文件log4netConfig.xml

step3:启用日志

private ILog Logger = null;
string logconfigpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4netConfig.xml");
            FileInfo logfile = new FileInfo(logconfigpath);
            log4net.Config.XmlConfigurator.ConfigureAndWatch(logfile);
            Logger = LogManager.GetLogger("DeleteImage");

其中ConfigureAndWatch的作用是:Configures log4net using the file specified, monitors the file for changes and reloads the configuration if a change is detected.

实例:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;
using log4net.Appender;

namespace CommonLogger
{
    public class Logger
    {
        public static ILog _log = null;
        public static Logger Instance = new Logger();
        private Logger()
        {
            Initialize();
        }

        public static void Initialize()
        {
            string cfg = string.Empty;
            if (!string.IsNullOrWhiteSpace(Log4netConfigFile))
            {
                cfg = Log4netConfigFile;
            }
            else
            {
                string[] names = new string[] { "log4netConfig.xml", "log4net.xml" };
                string currentDir = AppDomain.CurrentDomain.BaseDirectory;
                string configDir = Path.Combine(currentDir, "config");
                foreach (var n in names)
                {
                    cfg = Path.Combine(configDir, n);
                    if (File.Exists(cfg))
                        goto label1;
                }
                foreach (var n in names)
                {
                    cfg = Path.Combine(currentDir, n);
                    if (File.Exists(cfg))
                        goto label1;
                }

                //cfg = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4netConfig.xml");
                //if (!File.Exists(cfg))
                //{
                //    cfg = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.xml");
                //    if (!File.Exists(cfg))
                //        throw new FileNotFoundException("log4netConfig.xml or log4net.xml");
                //}
            }
        label1:
            if (!File.Exists(cfg))
                throw new FileNotFoundException("log4netConfig.xml or log4net.xml");
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(cfg));
            UpdateLogPath();

            _log = LogManager.GetLogger(Assembly.GetExecutingAssembly().FullName);

            StringBuilder builder = new StringBuilder();
            builder.AppendLine();
            builder.AppendLine("****************************************************************");
            builder.AppendLine("****************************************************************");
            builder.AppendLine("***                                                          ***");
            builder.AppendLine("***                                                          ***");
            string name = System.Diagnostics.Process.GetCurrentProcess().ProcessName;

            int lft = 0;
            lft = 56 - name.Length;
            int padleft = 0;
            int padright = 0;
            if (lft > 0)
            {
                padleft = lft / 2;
                padright = lft - padleft;
            }
            builder.AppendLine("*** " + name.PadLeft(name.Length + padleft, ' ').PadRight(padleft + name.Length + padright, ' ') + " ***");
            builder.AppendLine("***                                                          ***");
            builder.AppendLine("***                                                          ***");
            builder.AppendLine("****************************************************************");
            builder.AppendLine("****************************************************************");
            Logger.Info(builder.ToString());
        }
        public static string Log4netConfigFile { get; set; }
        public static void UpdateLogPath()
        {
            var hier = log4net.LogManager.GetRepository() as log4net.Repository.Hierarchy.Hierarchy;
            if (hier == null)
                return;
            var appendders = hier.GetAppenders();
            foreach (var appender in appendders)
            {

                var rollingfileappender = appender as RollingFileAppender;
                if (rollingfileappender != null)
                {
                    rollingfileappender.RollingStyle = RollingFileAppender.RollingMode.Composite;
                    string path = Path.Combine(Path.GetDirectoryName(rollingfileappender.File), Process.GetCurrentProcess().ProcessName) + "\\";
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
                    rollingfileappender.File = path;
                    rollingfileappender.ActivateOptions();
                }
            }
        }

        public static void Debug(object message)
        {
            Debug(message, null);
        }

        public static void Debug(object message, Exception ex)
        {
            if (_log != null)
                _log.Debug(message, ex);
        }

        public static void DebugWithFormat(string format, params object[] args)
        {
            if (_log != null)
                _log.DebugFormat(format, args);
        }

        public static void Info(object message)
        {
            Info(message, null);
        }

        public static void Info(object message, Exception ex)
        {
            if (_log != null)
                _log.Info(message, ex);
        }

        public static void InfoWithFormat(string format, params object[] args)
        {
            if (_log != null)
                _log.InfoFormat(format, args);
        }

        public static void Warn(object message)
        {
            Warn(message, null);
        }

        public static void Warn(object message, Exception ex)
        {
            if (_log != null)
                _log.Warn(message, ex);
        }

        public static void WarnWithFormat(string format, params object[] args)
        {
            if (_log != null)
                _log.WarnFormat(format, args);
        }

        public static void Error(object message)
        {
            Error(message, null);
        }

        public static void Error(object message, Exception ex)
        {
            if (_log != null)
                _log.Error(message, ex);
        }

        public static void ErrorWithFormat(string format, params object[] args)
        {
            if (_log != null)
                _log.ErrorFormat(format, args);
        }

        public static void Fatal(object message)
        {
            Fatal(message, null);
        }

        public static void Fatal(object message, Exception ex)
        {
            if (_log != null)
                _log.Fatal(message, ex);
        }

        public static void FatalWithFormat(string format, params object[] args)
        {
            if (_log != null)
                _log.FatalFormat(format, args);
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值