日志管理——log4net的应用

log4Net的应用


Log4net是针对.Net.日志类库,并且稳定。其功能还是挺强大的,可将日志分不同的等级,以不同的样式,将日志输出到不同的媒介。使用过程中,主要还是在于配置文件的配置。

一、添加log4net组件


二、定义一个接口
public interface ILogService
    {
        /// <summary>
        /// 写本地及服务器日志
        /// </summary>
        /// <param name="model"></param>
        void Log(Log model);
        void Log(List<Log> list);

        /// <summary>
        /// 写本地日志
        /// </summary>
        /// <param name="model"></param>
        void Log2Local(Log model);
        void Log2Local(List<Log> list);

        /// <summary>
        /// 写服务器日志
        /// </summary>
        /// <param name="model"></param>
        void Log2Server(Log model);
        void Log2Server(List<Log> list);
    }

 

三、定义一个记录日志实体
public class Log
    {
        /// <summary>
        /// 日志ID
        /// </summary>
        public string Id
        {
            get;
            set;
        }

        /// <summary>
        /// 来源
        /// </summary>
        public string Item
        {
            get;
            set;
        }

        /// <summary>
        /// 用户ID
        /// </summary>
        public string UserId
        {
            get;
            set;
        }

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get;
            set;
        }

        /// <summary>
        /// 日志概述
        /// </summary>
        public string Summary
        {
            get;
            set;
        }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime LogTime
        {
            get;
            set;
        }

        /// <summary>
        /// 日志级别
        /// </summary>
        public string Level
        {
            get;
            set;
        }

        /// <summary>
        /// 动作
        /// </summary>
        public string Action
        {
            get;
            set;
        }

        public override string ToString()
        {
            return String.Format("日志级别:{0}  记录时间:{1}  来源名称:{2}  动作:{3}  描述:{4}",
                       Level,
                       LogTime.ToString(),
                       Item,
                       Action,
                       Summary);
        }
    }


四、实现定义的接口
    public class LogService:ILogService
    {
        log4net.ILog logger = null;
        Dictionary<LogAction, String> ActionDictionary = new Dictionary<LogAction, String>();
        Dictionary<LogLevel, String> LevelDictionary = new Dictionary<LogLevel, String>();

        public LogService()
        {
            BuildDirectory();
            BuildEnumString();
            logger = LogManager.GetLogger("TestLog");
        }

        /// <summary>
        /// 创建存放日志的文件夹及文件
        /// </summary>
        protected void BuildDirectory()
        {
            string folder = ConfigurationManager.AppSettings["LogFile"].Split('\\')[0];
            string fullFolder = Path.Combine(Application.StartupPath, folder);
            string logfilePath = Path.Combine(Application.StartupPath,
                ConfigurationManager.AppSettings["LogFile"]);

            if (!Directory.Exists(fullFolder))
            {
                Directory.CreateDirectory(fullFolder);
            }
            if (!File.Exists(logfilePath))
            {
                File.Create(logfilePath);
            }
        }

        /// <summary>
        /// 设置枚举的字符串化值
        /// </summary>
        protected void BuildEnumString()
        {
            ActionDictionary.Add(LogAction.INSERT, "新增");
            ActionDictionary.Add(LogAction.DELETE, "删除");
            ActionDictionary.Add(LogAction.UPDATE, "修改");
            ActionDictionary.Add(LogAction.UNKNOWN, "其他");

            LevelDictionary.Add(LogLevel.INFO, "信息");
            LevelDictionary.Add(LogLevel.WARN, "警告");
            LevelDictionary.Add(LogLevel.ERROR, "错误");
            LevelDictionary.Add(LogLevel.FATAL, "致命错误");
            LevelDictionary.Add(LogLevel.UNKNOWN, "未定义级别");
        }

        #region ILogService 成员

        public void Log(Log model)
        {
            throw new NotImplementedException();
        }

        public void Log(List<Log> list)
        {
            throw new NotImplementedException();
        }

        public void Log2Local(Log model)
        {
            LogLevel level =(LogLevel) Enum.Parse(typeof(LogLevel), model.Level) ;
            model.Level = LevelDictionary[level];
            switch (level)
            {
                case LogLevel.INFO:
                    logger.Info(model.ToString());
                    break;
                case LogLevel.ERROR:
                    logger.Error(model.ToString());
                    break;
                case LogLevel.FATAL:
                    logger.Fatal(model.ToString());
                    break;
                case LogLevel.WARN:
                    logger.Warn(model.ToString());
                    break;
                case LogLevel.UNKNOWN:
                    logger.Info(model.ToString());
                    break;
                default:
                    break;
            }
        }

        public void Log2Local(List<Log> list)
        {
            throw new NotImplementedException();
        }

        public void Log2Server(Log model)
        {
            throw new NotImplementedException();
        }

        public void Log2Server(List<Log> list)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    /// <summary>
    /// 日志级别
    /// </summary>
    public enum LogLevel
    {
        /// <summary>
        /// 信息
        /// </summary>
        INFO,
        /// <summary>
        /// 警告
        /// </summary>
        WARN,
        /// <summary>
        /// 错误
        /// </summary>
        ERROR,
        /// <summary>
        /// 致命错误
        /// </summary>
        FATAL,
        /// <summary>
        /// 未定义级别
        /// </summary>
        UNKNOWN
    }

    /// <summary>
    /// 日志动作
    /// </summary>
    public enum LogAction
    {
        /// <summary>
        /// 新增动作
        /// </summary>
        INSERT,
        /// <summary>
        /// 更新动作
        /// </summary>
        UPDATE,
        /// <summary>
        /// 删除动作
        /// </summary>
        DELETE,
        /// <summary>
        /// 未定义动作
        /// </summary>
        UNKNOWN
    }

五、将创建好的类拿来用
添加配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="System.Configuration.Log4NetConfigurationSectionHandler" />
  </configSections>
  <appSettings>
    <add key="LogFile" value="log\log.txt"/>
  </appSettings>

  <log4net>
    <logger name="TestLog">
      <level value="ALL"/>
      <appender-ref ref="FileAppender" />
    </logger>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="log\log.txt" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <ConversionPattern value="%message%newline" />
      </layout>
    </appender>
  </log4net>
 
</configuration>
重点在于节点<configSections>与<log4net>的配置。

注意在AssemblyInfo.cs中添加[assembly: log4net.Config.XmlConfigurator(ConfigFile = "App.config", Watch = true)]
使其能自动寻找配置文件里面的配置信息。

 

六。测试
   LogService log = new LogService();
            Log model = new Log();
            model.Id = Guid.NewGuid().ToString();
            model.Level = LogLevel.INFO.ToString();
            model.LogTime = DateTime.Now;
            model.Summary = textBox1.Text;
            model.Action = LogAction.INSERT.ToString();
            log.Log2Local(model);

posted @ 2010-02-04 15:31  wakerobin  阅读(748)  评论(2编辑  收藏  举报