随笔 - 410  文章 - 0  评论 - 519  阅读 - 148万 

  这个日志类是基于企业库来封装的,首先贴上配置文件的代码。

复制代码
View Code
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>
  <loggingConfiguration name="Logging Application Block" tracingEnabled="true"
    defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
    <listeners>
      <add name="EventLog Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging"
        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging"
        source="Enterprise Library Logging" formatter="Text Formatter"
        log="Application" machineName="" traceOutputOptions="None" filter="All" />
      <add name="Rolling File Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging"
        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging"
        fileName=".\RollingFlatFile.log" footer="----------------------------------------"
        formatter="Text Formatter" header="----------------------------------------"
        rollFileExistsBehavior="Increment" rollInterval="Midnight" rollSizeKB="1024"
        timeStampPattern="yyyy-MM-dd" maxArchivedFiles="3" traceOutputOptions="None"
        filter="All" />
    </listeners>
    <formatters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging"
        template="Timestamp: {timestamp(local)}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}ActivityId: {property(ActivityId)}{newline}Severity: {severity}{newline}Title:{title}{newline}"
        name="Brief Format Text" />
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging"
        template="Timestamp: {timestamp(local)}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}Severity: {severity}{newline}Title: {title}{newline}Activity ID: {property(ActivityId)}{newline}Machine: {localMachine}{newline}App Domain: {localAppDomain}{newline}ProcessId: {localProcessId}{newline}Process Name: {localProcessName}{newline}Thread Name: {threadName}{newline}Win32 ThreadId:{win32ThreadId}{newline}Extended Properties: {dictionary({key} - {value}{newline})}"
        name="Text Formatter" />
    </formatters>
    <logFilters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.PriorityFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
        minimumPriority="2" maximumPriority="99" name="Priority Filter" />
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.LogEnabledFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
        enabled="true" name="LogEnabled Filter" />
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.CategoryFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
        categoryFilterMode="AllowAllExceptDenied" name="Category Filter" />
    </logFilters>
    <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="EventLog Listener" />
          <add name="Rolling File Listener" />
        </listeners>
      </add>
      <add switchValue="All" name="ExceptionHandling">
        <listeners>
          <add name="EventLog Listener" />
          <add name="Rolling File Listener" />
        </listeners>
      </add>
    </categorySources>
    <specialSources>
      <allEvents switchValue="All" name="All Events" />
      <notProcessed switchValue="All" name="Unprocessed Category" />
      <errors switchValue="All" name="Logging Errors &amp; Warnings">
        <listeners>
          <add name="EventLog Listener" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>
</configuration>
复制代码

  日志类使用了单例模式,并且对外公开了两个方法,代码如下:

复制代码
namespace Tmac.Utilities
{
    /// <summary>
    /// 日志操作类
    /// </summary>
    public sealed class LogUtil
    {
        //单例模式
        private static readonly LogUtil logUtil = new LogUtil();
        private LogUtil() { }

        public static LogUtil Instance
        {
            get
            {
                return logUtil;
            }
        }

        public static void WriteLog(TraceEventType traceEventType, string msg)
        {
            try
            {
                LogEntry log = new LogEntry();
                log.TimeStamp = DateTime.Now;
                log.Severity = traceEventType;
                log.Message = msg;
                Logger.Write(log);
            }
            catch (Exception ex)
            { }
        }

        public static void WriteLog(TraceEventType traceEventType, string msg,string category)
        {
            try
            {
                LogEntry log = new LogEntry();
                log.TimeStamp = DateTime.Now;
                log.Severity = traceEventType;
                log.Message = msg;
                log.Categories = new string[] { category};//指定策略,不指定默认为General
                Logger.Write(log);
            }
            catch (Exception ex)
            { }
        }
    }
}
复制代码

 

posted on   永远的麦子  阅读(3176)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示