如何在其他项目中添加NLog类库项目

sha*_*ath 6 c# nlog


我已经在C#中创建了一个控制台项目,在该项目中,我正在使用NLog进行日志记录。
当我运行该项目时,它成功登录到多个目标,例如控制台,文件,EventLog以及Sentinal。
但是,当我将该项目作为classLibrary并尝试将引用添加到另一个项目时,它并没有记录到任何目标。当然,项目中没有错误。
以下是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using NLog.Config;

namespace NLogger
{
public class logWrapper
{
    private static Logger logger = LogManager.GetCurrentClassLogger();
    public void LevelLogger(string level, string msg)
    {
        if (level == "Trace")
            Trace(msg);
        else if (level == "Info")
            Info(msg);
        else if (level == "Error")
            Error(msg);
        else if (level == "Debug")
            Debug(msg);
        else if (level == "Warn")
            Warn(msg);
    }

    public void Trace(string msg)
    {
        try
        {
            logger.Trace(msg);
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    public void Info(string msg)
    {
        logger.Info(msg);
    }

    public void Error(string msg)
    {
        logger.Error(msg);
    }
    public void Debug(string msg)
    {
        logger.Debug(msg);
    }
    public void Warn(string msg)
    {
        logger.Warn(msg);
    }

    //Uncomment following when the project type is Console App. --Debugging purpose only

    //public static void Main(string[] args)
    //{
    //    logWrapper l = new logWrapper();
    //    l.LevelLogger("Info", "INFORMATION");
    //}
}
}
Run Code Online (Sandbox Code Playgroud)

以下是Nlog.config文件:

<?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" >
<targets>
<target xsi:type="File" name="file" layout="${longdate}|${level}|${message}|${callsite:fileName=true}${newLine}"
        fileName="C:\Users\sharathk\Desktop\ToCompare\${shortdate}_Log.txt"/>
<target name="viewer" xsi:type="NLogViewer" address="udp://10.100.18.166:9999"/>
<target xsi:type="EventLog" name="event" layout="${longdate}|${level}|${message}|${callsite:fileName=true}" source="NLogger"/>
<target name="console" xsi:type="Console"
        layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />
 </targets>

 <rules>
  <!-- add your logging rules here -->
 <logger name="*" minlevel="Trace" writeTo="file,event,viewer,console" />
 </rules>
</nlog>
Run Code Online (Sandbox Code Playgroud)

我将此项目dll添加到另一个项目中,并且没有错误。

我正在创建logWrapper类的对象,并调用方法来记录信息,但是它根本无法正常工作。请让我知道我在这里犯的错误。

Jos*_*Lee 6

为什么它没有运行:您的NEW项目是否具有该NLog.config文件?

如果您需要从单个nlog.config加载所有项目,则:

NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration( "<your path>" + "\\NLog.config", true);
Run Code Online (Sandbox Code Playgroud)