为log4net创建一个帮助器类

时间:2016-03-09 06:41:14

标签: c# log4net

我正在尝试为log4net创建一个Helper类,它会将我的所有消息记录到日志文件中。

该解决方案由MVC Web应用程序和2个Windows服务组成。我希望能够为所有三个项目使用相同的记录器类。

我正在创建的助手类是在共同项目中。

这就是班级的样子:

public class TBLogger 
{
    private static ILog Logger;

    public ILog Log
    {
        get
        {
            if (Logger != null) return Logger;
            XmlConfigurator.Configure();

            var type = MethodBase.GetCurrentMethod().DeclaringType;
            Logger = LogManager.GetLogger(type);
            return Logger;
        }
    }

    public void LogMessage(MessageType messageType, string message)
    {
        switch (messageType)
        {
            case MessageType.Debug:
                Log.Debug(message);
                break;

            case MessageType.Information:
                Log.Info(message);
                break;

            case MessageType.Error:
                Log.Error(message);
                break;
        }
    }

    public void LogExceptionMessage(string message, Exception innerException, string stackTrace, int iStage)
    {
        var exceptionMessage = string.Format("iStage: [{0}] Exception: [{1}], Inner: [{2}], Stack Trace: [{3}]", iStage, message, innerException.Message, stackTrace);
        Log.Error(exceptionMessage);
    }
}

我在程序集类中添加了Log4net设置

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4net.config", Watch = true)]

配置文件如下所示: (用于MVC应用程序的web.config和用于服务的App.config)

<log4net file="Log4net.config" />

Log4net.config是这样的:

<log4net>

  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="D:\MyPath\Logs\WebLogs\" />
    <datePattern value="dd-MMM-yyyy\\\\'GeneralLog.txt'" />
    <staticLogFileName value="false" />
    <appendToFile value="true" />
    <rollingStyle value="Composite" />
    <layout type="log4net.Layout.PatternLayout">
      <!--<conversionPattern value="%date{MM/dd/yy HH:mm} [%thread] %-5level - %message%newline" />-->
      <conversionPattern value="%date{MM/dd/yy HH:mm} %-5level - %message%newline" />
    </layout>

    <filter type="log4net.Filter.LevelRangeFilter">
      <levelMin value="INFO" />
      <levelMax value="INFO" />
    </filter>

  </appender>
  <root>
    <appender-ref ref="RollingLogFileAppender" />
  </root>
</log4net>

我想要做的是创建一个TBLogger对象,并从Windows服务和MVC应用程序中调用LogMessage函数。

var logger = new TBLogger();
logger.LogMessage(MessageType.Information, "This is Information");

但它似乎没有起作用。

修改

log4net调试文件提供了以下信息:

log4net: log4net assembly [log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a]. Loaded from [C:\Users\[]\AppData\Local\Temp\Temporary ASP.NET Files\vs\bc22238d\7aa91eba\assembly\dl3\c228fa05\4ec3fa68_5175d101\log4net.dll]. (.NET Runtime [4.0.30319.42000] on Microsoft Windows NT 10.0.10240.0)
log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository for assembly [DotNetOpenAuth.Core, Version=4.3.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246]
log4net: Assembly [DotNetOpenAuth.Core, Version=4.3.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246] Loaded From [C:\Users\[]\AppData\Local\Temp\Temporary ASP.NET Files\vs\bc22238d\7aa91eba\assembly\dl3\a73bdbf7\3acfe046_5175d101\DotNetOpenAuth.Core.dll]
log4net: Assembly [DotNetOpenAuth.Core, Version=4.3.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246] does not have a RepositoryAttribute specified.
log4net: Assembly [DotNetOpenAuth.Core, Version=4.3.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository for assembly [Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]
log4net: Assembly [Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\Users\[]\AppData\Local\Temp\Temporary ASP.NET Files\vs\bc22238d\7aa91eba\assembly\dl3\e7a0face\f76e0d4c_cf79d101\Common.dll]
log4net: Assembly [Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: Assembly [Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: repository [log4net-default-repository] already exists, using repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: configuring repository [log4net-default-repository] using .config file section
log4net: Application config file is [C:..........\web.config]
log4net: Configuring Repository [log4net-default-repository]
log4net: Configuration update mode [Merge].
log4net: Hierarchy Threshold []
log4net: No appenders could be found for logger [Common.Constants.TBLogger] repository [log4net-default-repository]
log4net: Please initialize the log4net system properly.
log4net:     Current AppDomain context information: 
log4net:        BaseDirectory   : C:\.............\
log4net:        FriendlyName    : /LM/W3SVC/2/ROOT-1-131019801091897637
log4net:        DynamicDirectory: C:\Users\[]\AppData\Local\Temp\Temporary ASP.NET Files\vs\bc22238d\7aa91eba

编辑2: 当我将这些行添加到 Global.asax.cs

时,它适用于MVC应用程序
var l4net = Server.MapPath("~/Log4net.config");
log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(l4net));

2 个答案:

答案 0 :(得分:1)

正如我在评论中所怀疑的,问题是log4net无法找到配置文件。这可能是因为应用程序是一个Web应用程序,您站点的根目录不是应用程序基目录。因此,仅指定“log4net.config”作为配置文件名将无效。

Log4net支持web.config中的配置。您可以在那里配置记录器,而无需先找到站点的根目录。

这里有一点需要注意:更改web.config通常会重启您的Web应用程序。因此,如果您只是重新配置一些日志记录详细信息,那么您的Web应用程与ConfigureAndWatch一起使用的专用log4net配置文件将使您能够解决此问题,更改日志记录配置而无需重新启动应用程序。但正如您已经注意到的,您必须在代码中配置log4net,因为您必须先找到站点目录。我不知道你的情况是否存在问题,但我想指出它。

答案 1 :(得分:-2)

请尝试Nlog插件,它比Log4Net更好,它将支持多个板块形式。 当你的应用程序进入睡眠模式而不是唤醒Log4Net无法正常工作我面临一段时间问题这么多时间,这就是我切换到nLog的原因。 这对你有所帮助。 请查看以下代码,这在我的项目中完美运行。

    /// <summary>
    /// Log Class For nLog
    /// </summary>
    internal static class Log
    {
        public static Logger Instance { get; private set; }
        static Log()
        {
            LogManager.ReconfigExistingLoggers();

            Instance = LogManager.GetCurrentClassLogger();
        }
    }


    /// <summary>
    /// custom Logger Class gor Logger
    /// </summary>
    public static class Loggers
    {
        /// <summary>
        /// Static Mathod For Info Message
        /// </summary>
        /// <param name="Message"></param>
        public static void Info(string Message)
        {
            Log.Instance.Info(Message);
        }
        /// <summary>
        /// Static Method For Error Logger
        /// </summary>
        /// <param name="Ex"></param>
        public static void Error(Exception Ex)
        {
            Log.Instance.Error(Ex);
        }

        /// <summary>
        /// Static Method For Debug
        /// </summary>
        /// <param name="Message"></param>
        public static void Debug(string Message)
        {
            Log.Instance.Debug(Message);
        }
    }

比较配置文件

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Trace" internalLogFile="${basedir:dir=Logs}\nlog-internal.log" >


  <!-- optional, add some variabeles
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <variable name="myvar" value="myvalue"/>

  <!-- 
  See https://github.com/nlog/nlog/wiki/Configuration-file 
  for information on customizing logging rules and outputs.
   -->

  <variable name="appName" value="ATR.MOBILE.Web" />
  <targets>
    <target xsi:type="File"
               name="default"
               layout="${longdate} - ${level:uppercase=true}:${message}${onexception:${newline}EXCEPTION\: ${exception:format=ToString}}"
               fileName="${basedir:dir=Logs}\Debug.log"
               keepFileOpen="false"
               archiveFileName="
            ${basedir:dir=Logs}\Debug_${shortdate}.{##}.log"
               archiveNumbering="Sequence"
               archiveEvery="Day"
               maxArchiveFiles="30"
            />

    <target xsi:type="EventLog"
            name="eventlog"
            source="${appName}"
            layout="${message}${newline}${exception:format=ToString}"/>
    <!-- 
    add your targets here 
    See https://github.com/nlog/NLog/wiki/Targets for possible targets.
    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
    -->

    <!--
    Writing events to the a file with the date in the filename. 
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->
  </targets>

  <rules>
    <!-- add your logging rules here -->

    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
    <logger name="*" writeTo="default" minlevel="Info" />
    <logger name="*" writeTo="eventlog" minlevel="Error" />
  </rules>
</nlog>

示例:

Loggers.Info("Your comment.");
Loggers.Error(ex);