如何通过Nlog通过电子邮件发送整个日志文件

时间:2011-12-04 22:41:08

标签: vb.net nlog

Salvete! nLog for .NET具有将日志条目作为电子邮件发送的功能。但是,如果我们想要发送整个当前日志文件,那么如何将日志文件读入字符串并将其作为nLog {$message}传递呢?我没有看到nLog在其mailtarget附件中有一个属性用于附件。怎么办呢?

2 个答案:

答案 0 :(得分:2)

我今天刚刚用C#做过这个。我按照arkmuetz提供的答案How to get path of current target file using NLog in runtime?来首先获取Nlog目标的文件名。然后我读取文件并将文件的内容复制到另一个Nlog目标,该目标通过电子邮件发送邮件正文中的日志。

首先我创建了一个NlogHelper类

public static class NlogHelper
{

    /// <summary>
    /// Gets LogFileName by TargetName
    /// </summary>
    /// <param name="targetName">The nLog targetname for the specified logger.</param>
    /// <returns></returns>
    /// <remarks>https://stackoverflow.com/questions/11452645/how-to-get-path-of-current-target-file-using-nlog-in-runtime</remarks>
    public static 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;
    }
}

接下来,我在构造函数中检索了文件名并将其存储起来供以后使用。

_logLileName = NlogHelper.GetLogFileName("DailyFile");

出于我的目的,我创建了一个属性,后来我用它来检索日志文件的内容。

public string LogFileContent
    {
        get
        {
            return File.ReadAllText(_logLileName);
        }
    }

最后,我将文件的内容添加到要通过电子邮件发送的日志中。

_logger.Error("Excel Builder LinkShare Error encountered -- Some companies did not complete succesfully!.  Please review logs. \n" + mfb.LogFileContent);

这是我的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 name="console" xsi:type="ColoredConsole"
 layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />
<target name="file" xsi:type="File" fileName="${basedir}/DomoExcelBuilderLog.txt"
 layout="${stacktrace} ${message}" />
<target name="DailyFile" xsi:type="File" fileName="C:\Temp\Log${shortdate}.txt"
 layout="${date:format=HH\:mm\:ss} --> ${message}" deleteOldFileOnStartup="true" />
<target name="file2" xsi:type="File" fileName="${basedir}/ServiceLog.txt"
 layout="${stacktrace} ${message}" />
<target name="MyMailer" xsi:type="Mail"
        smtpServer="some.server.com"
        smtpPort="587"
        smtpAuthentication="Basic"
        smtpUsername="no-reply"
        smtpPassword="somepassword"
        enableSsl="true"
        from="no-reply@some.server.com"
        to="myemail@gmail.com"/>
</targets>
<rules>
<logger name="MultipleFileBuilder" minlevel="Trace" writeTo="DailyFile" />
<logger name="ExcelBuilderService" minlevel="Debug" writeto="MyMailer" />
</rules>
</nlog>

我的应用程序首先登录名为“MultipleFileBuilder”的记录器。然后我使用NLogHelper类来检索Target'DailiyFile'的内容。

希望这有助于某人。

(注意:我删除了检查以查看文件是否存在于'GetLogFileName'方法中,因为在我的情况下文件不存在。)

答案 1 :(得分:0)

我认为您可以使用目标组合:默认目标+ MethodCall,然后手动发送电子邮件或使用Mail + Buffering发送一批记录。