无法创建日志文件

时间:2017-07-11 09:21:28

标签: wpf logging mvvm prism

我正在使用下面的代码,使用PRISM ILoggrFacade在我的项目中创建日志记录。 但我不确定这是最好的方法,第二件事我如何使用CustomLogger类日志记录,因为我无法创建日志记录。

public class CustomLogger : ILoggerFacade
    {

        protected static readonly ILog log = LogManager.GetLogger(typeof(CustomLogger));
        public CustomLogger()
        {
            log4net.Config.XmlConfigurator.Configure();
        }

        public void Log(string message, Category category, Priority priority)
        {
            switch (category)
            {
                case Category.Debug:
                    log.Debug(message);
                    break;
                case Category.Warn:
                    log.Warn(message);
                    break;
                case Category.Exception:
                    log.Error(message);
                    break;
                case Category.Info:
                    log.Info(message);
                    break;
            }
        }
    }

引导程序

 private readonly CustomLogger _logger = new CustomLogger();
 protected override ILoggerFacade CreateLogger()
        {
            return _logger;
        }

视图模型

            logger.Log("Logging success", Category.Info, Priority.None);

log4net.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
  </configSections>
  <log4net>
    <root>
      <level value="DEBUG" />
      <appender-ref ref="LogFileAppender" />
    </root>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="C:\temp\log.txt" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date [%thread] %message%newline" />
      </layout>
    </appender>
  </log4net>
</configuration>

1 个答案:

答案 0 :(得分:0)

以上代码的问题是需要在汇编中配置log4net,如下所示:

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

另外如果您想在ViewModels中拖动log4net,请使用以下代码

 private readonly ILoggerFacade _loggerFacade;
 public ContentAViewViewModel(ILoggerFacade loggerFacade)
        {
          _loggerFacade = loggerFacade;
        }

示例

    private void LoadPeople()
        {
        _loggerFacade.Log("Load People", Category.Debug, Priority.High);
        }