很久之前研究微软的企业库时候写的,要注意需要引用Microsoft.Practices.EnterpriseLibrary.Logging组件库,因为ASP.NET5出来,微软在.netframework中自带了Logger,所以应该以后也不会用上。
using System;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Linq;using System.Text;using Microsoft.Practices.EnterpriseLibrary.Logging;using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;namespace Enuo.Core.Log{ ////// 标题:微软企业库日志模块调用类 /// 描述:目前适用Enterprise6.0 /// 作者:sunjipeng /// 日期:2013-12-24 /// public class EnterpriseLibraryLogger { #region Variables static LogWriter logwriter; static LoggingConfiguration config; //static LogWriterFactory factory; static string headerstyle = "------------Log--------------"; #endregion #region Ctors static EnterpriseLibraryLogger() { TextFormatter brie = new TextFormatter(); var flatFileTraceListener = new FlatFileTraceListener(DefaultDirectory, headerstyle, string.Empty, brie); config = new LoggingConfiguration(); config.AddLogSource("mylog", SourceLevels.All, true).AddTraceListener(flatFileTraceListener); logwriter = new LogWriter(config); } #endregion #region Property Getter Setter ////// 默认的日志路径 /// public static string DefaultDirectory { get { string dirname = "AppLog"; string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,dirname); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } return dir; } } #endregion #region Public Methods ////// 写入调试跟踪日志 /// public static void WriteDebug(string msg) { if(logwriter.IsLoggingEnabled()) { LogEntry entry = new LogEntry(); //事件号 entry.EventId = 9007; entry.Message = "日志信息"; //严重等级 entry.Priority = 9; entry.Severity = TraceEventType.Verbose; entry.Categories.Add("种类"); logwriter.Write(entry); } } ////// 写入普通消息日志 /// public void WriteInfo() { LogEntry entry = new LogEntry(); entry.Severity = TraceEventType.Information; logwriter.Write(entry); } ////// 写入可恢复错误日志 /// public void WriteError() { LogEntry entry = new LogEntry(); entry.Severity = TraceEventType.Error; logwriter.Write(entry); } ////// 写入错误或应用程序崩溃日志 /// public void WriteCritical() { LogEntry entry = new LogEntry(); entry.Severity = TraceEventType.Critical; logwriter.Write(entry); } #endregion }}