本文介绍了NLog自定义FileTarget的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为Sentinel制作了自定义NLogViewerTarget( NLogViewerEx ),如下所示: https: //stackoverflow.com/a/15519783/6229375

I have made a custom NLogViewerTarget (NLogViewerEx) for Sentinel like this: https://stackoverflow.com/a/15519783/6229375

现在,我也想为我的FileTarget使用格式化的消息,但是当我应用它时,它不再起作用(记录).

Now I also want to have the formatted Message for my FileTarget, but when I apply it, it is not working (logging) anymore.

<targets async="true">
    <target
      xsi:type="FileTargetEx"
      name="file"
      layout="${longdate} - ${level:uppercase=true}: ${message}${onexception:${newline}exception\: ${exception:format=tostring}}"
      filename="${specialfolder:folder=commonapplicationdata}/company gmbh/${appname}/logs/${appname}.log"
      keepfileopen="false"
      archivefilename="${specialfolder:folder=commonapplicationdata}/company gmbh/${appname}/logs/${appname}_archive.{##}.zip"
      archivenumbering="dateandsequence"
      archiveevery="day"
      maxarchivefiles="50"
      archivedateformat="yyyy-mm-dd"
      archiveoldfileonstartup="true"
      createdirs="true"
      enablearchivefilecompression="true"
      encoding="utf-8"
      header="############################################## ${appname} log ##############################################"
      archiveabovesize="10485760"/>


    <target xsi:type="NLogViewerEx"
              name="sentinel"
              address="udp://127.0.0.1:9999"/>
  </targets>

我也尝试过创建自定义FileTarget,但这也无法正常工作.有人有解决方案,如何应用吗?

I have also tried to make a custom FileTarget, but this is also not working. Does someone has got a solution how to apply it?

[Target("FileTargetEx")]
internal class FileTargetEx : FileTarget
{
    private readonly Log4JXmlEventLayoutEx _Layout = new Log4JXmlEventLayoutEx();

    public override Layout Layout { get { return _Layout; } set { } }
}

我给了File Targetxsi:type FileTargetExxsi:type NLogViewerEx,但没有成功.如果这样做,Sentinel和File将不再记录日志!

I gave the File Target the xsi:type FileTargetEx and xsi:type NLogViewerEx, without any success. If I do so, Sentinel and File is not logging anymore!

启用内部调试日志后,我得到以下日志:

After enabling the internal debug log, I get the following log:

2017-12-13 09:32:52.6572 Info Loading assembly: HtCore
2017-12-13 09:32:52.6834 Debug ScanAssembly('NLog, Version=5.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c')
2017-12-13 09:32:52.7356 Debug Start auto loading, location: D:\Repositories\gitlab.company\dotNet\HtCore\HtCore\TestConsole\bin\Debug
2017-12-13 09:32:52.7356 Debug Auto loading done
2017-12-13 09:32:52.7496 Debug ScanAssembly('HtCore, Version=1.4.0.8, Culture=neutral, PublicKeyToken=null')
2017-12-13 09:32:52.7797 Debug Setting 'UppercaseLayoutRendererWrapper.uppercase' to 'true'
2017-12-13 09:32:52.7797 Debug Setting 'FileTargetEx.name' to 'file'
2017-12-13 09:32:52.7978 Debug Setting 'FileTargetEx.filename' to '${specialfolder:folder=commonapplicationdata}/company gmbh/Testconsole/logs/Testconsole.log'
2017-12-13 09:32:52.7978 Debug Setting 'SpecialFolderLayoutRenderer.folder' to 'commonapplicationdata'
2017-12-13 09:32:52.8108 Debug Setting 'FileTargetEx.keepfileopen' to 'false'
2017-12-13 09:32:52.8108 Debug Setting 'FileTargetEx.archivefilename' to '${specialfolder:folder=commonapplicationdata}/company gmbh/Testconsole/logs/Testconsole_archive.{##}.zip'
2017-12-13 09:32:52.8108 Debug Setting 'SpecialFolderLayoutRenderer.folder' to 'commonapplicationdata'
2017-12-13 09:32:52.8278 Debug Setting 'FileTargetEx.archivenumbering' to 'dateandsequence'
2017-12-13 09:32:52.8278 Debug Setting 'FileTargetEx.archiveevery' to 'day'
2017-12-13 09:32:52.8429 Debug Setting 'FileTargetEx.maxarchivefiles' to '50'
2017-12-13 09:32:52.8429 Debug Setting 'FileTargetEx.archivedateformat' to 'yyyy-mm-dd'
2017-12-13 09:32:52.8429 Debug Setting 'FileTargetEx.archiveoldfileonstartup' to 'true'
2017-12-13 09:32:52.8634 Debug Setting 'FileTargetEx.createdirs' to 'true'
2017-12-13 09:32:52.8634 Debug Setting 'FileTargetEx.enablearchivefilecompression' to 'true'
2017-12-13 09:32:52.8758 Debug Setting 'FileTargetEx.encoding' to 'utf-8'
2017-12-13 09:32:52.8758 Debug Setting 'FileTargetEx.header' to '############################################## Testconsole log ##############################################'
2017-12-13 09:32:52.8968 Warn Error when setting '############################################## ${appname} log ##############################################' on attibute 'header'
2017-12-13 09:32:52.9028 Error Parsing configuration from D:\Repositories\gitlab.company\dotNet\HtCore\HtCore\TestConsole\bin\Debug\NLog.config failed. Exception: NLog.NLogConfigurationException: Exception when parsing D:\Repositories\gitlab.company\dotNet\HtCore\HtCore\TestConsole\bin\Debug\NLog.config.  ---> NLog.NLogConfigurationException: Error when setting property 'Header' on FileTargetEx Target[file] ---> System.NullReferenceException: Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt.
   bei NLog.Targets.TargetWithLayoutHeaderAndFooter.set_Header(Layout value)
   --- Ende der internen Ausnahmestapelüberwachung ---
   bei NLog.Internal.PropertyHelper.SetPropertyFromString(Object obj, String propertyName, String value, ConfigurationItemFactory configurationItemFactory)
   bei NLog.Config.XmlLoggingConfiguration.ConfigureObjectFromAttributes(Object targetObject, NLogXmlElement element, Boolean ignoreType)
   bei NLog.Config.XmlLoggingConfiguration.ParseTargetElement(Target target, NLogXmlElement targetElement, Dictionary`2 typeNameToDefaultTargetParameters)
   bei NLog.Config.XmlLoggingConfiguration.ParseTargetsElement(NLogXmlElement targetsElement)
   bei NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String filePath, Boolean autoReloadDefault)
   bei NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String filePath, Boolean autoReloadDefault)
   bei NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
   --- Ende der internen Ausnahmestapelüberwachung ---
2017-12-13 09:32:52.9028 Debug --- NLog configuration dump ---

Nlog.conf

<?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"
  internalLogFile="c:\log.txt" 
  internalLogLevel="Debug">
  <extensions>
    <add assembly="HtCore"/>
  </extensions>
  <variable name="appname" value="Testconsole" />

  <targets async="true">
    <target
      xsi:type="FileTargetEx"
      name="file"
      filename="${specialfolder:folder=commonapplicationdata}/company gmbh/${appname}/logs/${appname}.log"
      keepfileopen="false"
      archivefilename="${specialfolder:folder=commonapplicationdata}/company gmbh/${appname}/logs/${appname}_archive.{##}.zip"
      archivenumbering="dateandsequence"
      archiveevery="day"
      maxarchivefiles="50"
      archivedateformat="yyyy-mm-dd"
      archiveoldfileonstartup="true"
      createdirs="true"
      enablearchivefilecompression="true"
      encoding="utf-8"
      header="############################################## ${appname} log ##############################################"
      archiveabovesize="10485760"/>


    <target xsi:type="NLogViewerEx"
              name="sentinel"
              address="udp://127.0.0.1:9999"/>
  </targets>
  <rules>
    <logger name="*" writeTo="file" minlevel="Info"/>
    <logger name="*" writeTo="sentinel" minlevel="Info"/>
  </rules>
</nlog>

C#类

[Target("FileTargetEx")]
internal class FileTargetEx : NLog.Targets.FileTarget
{
    private readonly FileLayout _Layout = new FileLayout();

    public override Layout Layout { get { return _Layout; } set { } }
}

internal class FileLayout : NLog.Layouts.SimpleLayout
{

}

我总是遇到相同的错误.我将FileLayout设置为Layout还是与Sentinel一起使用的其他Layout都没关系.

I'm always getting the same error. It does not matter if I set FileLayout as Layout or my other Layout I'm using with Sentinel.

取消注释Layout override时,它将加载NLog.conf.

When uncomment the Layout override, then it is loading the NLog.conf..

推荐答案

工作解决方案

如果有更好的解决方案,请告诉我!

Working Solution

If there is a better solution, let me know!

/// <summary>
/// is using the <see cref="FileLayoutEx"/> class.
/// </summary>
[Target("FileTargetEx")]
internal class FileTargetEx : FileTarget
{
    public override Layout Layout
    {
        get => _Layout;
        set
        {
            base.Layout = new FileLayoutEx((value as SimpleLayout).OriginalText);
            _Layout = new FileLayoutEx((value as SimpleLayout).OriginalText);
        }
    }
    private Layout _Layout;

    public FileTargetEx()
    {
        Footer = new FileLayoutEx();
        Header = new FileLayoutEx();
    }
}

/// <summary>
/// Provides a formated message (Exception included!).
/// </summary>
[Layout("FileLayoutEx")]
internal class FileLayoutEx : SimpleLayout
{
    public FileLayoutEx() { }

    public FileLayoutEx(string originalText) : base(originalText) { }

    protected override string GetFormattedMessage(LogEventInfo logEvent)
    {
        //Extension method is outsourced
        LogEventInfo updatedInfo = logEvent.GetFormattedMessage();
        return base.GetFormattedMessage(updatedInfo);
    }
}

NLog.conf目标

<target
  xsi:type="FileTargetEx"
  name="file"
  filename="${specialfolder:folder=commonapplicationdata}/company gmbh/${appname}/logs/${appname}.log"
  keepfileopen="false"
  archivefilename="${specialfolder:folder=commonapplicationdata}/company gmbh/${appname}/logs/${appname}_archive.{##}.zip"
  archivenumbering="dateandsequence"
  archiveevery="day"
  maxarchivefiles="50"
  archivedateformat="yyyy-mm-dd"
  archiveoldfileonstartup="true"
  createdirs="true"
  enablearchivefilecompression="true"
  encoding="utf-8"
  header="############################################## ${appname} log ##############################################"
  layout="${longdate}|${level:uppercase=true}|${logger}|${message}"
  archiveabovesize="10485760"/>

这篇关于NLog自定义FileTarget的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 07:46