How to get path of current target file using NLog in runtime?

前端 未结 4 1724
猫巷女王i
猫巷女王i 2021-01-31 07:36

I use NLog with next configuration:

  
    

        
4条回答
  •  长情又很酷
    2021-01-31 08:01

    I know that my answer is not exactly answering the question, but the most difficult thing is to find the right target and cast it properly, then we can access any properties. I also didn't find a question that would fit my answer thus posting here...

    This method will work even if you have set async="true" (i.e. your target is wrapped by an AsyncTargetWrapper or any TargetWrapper) in your NLog XML configuration:

    Using NLog Version: 3.1.0.0

    Runtime Version: 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;
            }
        }
    

    Usage for MailTarget named emailError

    var emailError = (MailTarget)FindTargetByName("emailError");
    emailError.SmtpServer = "" //you can set or get
    

提交回复
热议问题