61

我将 NLog 与下一个配置一起使用:

  <targets>
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="f" />
  </rules>

我试图获取(我检查,集合中只有一个 FileTarget)的FileName属性FileTarget

NLog.LogManager.GetCurrentClassLogger().Info("test");
var logFile = (from t in NLog.LogManager.Configuration.AllTargets
                where t is NLog.Targets.FileTarget
                select (NLog.Targets.FileTarget)t).FirstOrDefault();

但是 logFile.FileName 只包含文件名的模式,正是它在设置中指定的方式。

如何进入当前日志文件的运行时路径?

4

4 回答 4

75

这对我有用:

var fileTarget = (FileTarget) LogManager.Configuration.FindTargetByName("file");
// Need to set timestamp here if filename uses date. 
// For example - filename="${basedir}/logs/${shortdate}/trace.log"
var logEventInfo = new LogEventInfo {TimeStamp = DateTime.Now}; 
string fileName = fileTarget.FileName.Render(logEventInfo);
if (!File.Exists(fileName))
    throw new Exception("Log file does not exist.");
于 2012-07-24T10:57:27.777 回答
34

即使您在 NLog XML 配置中设置async="true"(即您的目标由 包裹),此方法也将起作用:AsyncTargetWrapper

    private string GetLogFileName(string targetName)
    {
        string fileName = null;

        if (LogManager.Configuration != null && LogManager.Configuration.ConfiguredNamedTargets.Count != 0)
        {
            Target target = LogManager.Configuration.FindTargetByName(targetName);
            if (target == null)
            {
                throw new Exception("Could not find target named: " + targetName);
            }

            FileTarget fileTarget = null;
            WrapperTargetBase wrapperTarget = target as WrapperTargetBase;

            // Unwrap the target if necessary.
            if (wrapperTarget == null)
            {
                fileTarget = target as FileTarget;
            }
            else
            {
                fileTarget = wrapperTarget.WrappedTarget as FileTarget;
            }

            if (fileTarget == null)
            {
                throw new Exception("Could not get a FileTarget from " + target.GetType());
            }

            var logEventInfo = new LogEventInfo { TimeStamp = DateTime.Now };
            fileName = fileTarget.FileName.Render(logEventInfo);
        }
        else
        {
            throw new Exception("LogManager contains no Configuration or there are no named targets");
        }

        if (!File.Exists(fileName))
        {
            throw new Exception("File " + fileName + " does not exist");
        }

        return fileName;
    }
于 2013-05-09T13:01:52.337 回答
4

目标可以被多次包装(在我的例子中我有一个过滤器),所以下面的代码片段是一种更通用的展开方法,适用于多个级别,并且不对目标名称做出假设。

Target target = LogManager.Configuration.FindTargetByName(targetName);
while ((target != null) && (target is WrapperTargetBase))
{
    target = (target as WrapperTargetBase).WrappedTarget;
}
于 2016-12-19T23:53:53.637 回答
2

我知道我的回答并没有完全回答问题,但最困难的是找到正确的目标并正确地转换它,然后我们可以访问任何属性。我也没有找到适合我的答案的问题,因此在这里发布......

即使您在 NLog XML 配置中设置async="true"(即您的目标由一个AsyncTargetWrapper或任何 TargetWrapper 包装),此方法也将起作用:

使用 NLog 版本:3.1.0.0

运行时版本:v4.0.30319

    private Target FindTargetByName(string targetName)
    {
        if (LogManager.Configuration == null)
            return null;

        Target t = LogManager.Configuration.FindTargetByName(targetName);

        if (t is NLog.Targets.Wrappers.WrapperTargetBase)
        {
            var list = LogManager.Configuration.AllTargets.ToList();
            t = list.Find(x => x.Name == targetName + "_wrapped");
            return t;
        }
        else
        {
            return t;
        }
    }

名为 emailError 的 MailTarget 的用法

var emailError = (MailTarget)FindTargetByName("emailError");
emailError.SmtpServer = "" //you can set or get
于 2015-01-23T00:34:33.700 回答