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

发布于 2024-12-19 06:58:32 字数 178 浏览 3 评论 0原文

萨尔维特! nLog for .NET 能够以电子邮件的形式发送日志条目。但是,如果我们想要发送整个当前日志文件,除了将日志文件读入字符串并将其作为 nLog {$message} 传递之外,该怎么办呢?我没有看到 nLog 在其 mailtarget 中有用于附件的属性。这怎么能做到呢?

Salvete! nLog for .NET has the capability to send log entries as email. But if we want to send the entire current log file, how can it be done, short of reading the log file into a string and passing that as an nLog {$message}? I don't see that nLog has a property in its mailtarget for attachments. How can this be done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最好是你 2024-12-26 06:58:32

我今天刚刚用 C# 做了这个。我按照arkmuetz在这里提供的答案 如何在运行时使用NLog获取当前目标文件的路径?首先获取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="[email protected]"
        to="[email protected]"/>
</targets>
<rules>
<logger name="MultipleFileBuilder" minlevel="Trace" writeTo="DailyFile" />
<logger name="ExcelBuilderService" minlevel="Debug" writeto="MyMailer" />
</rules>
</nlog>

我的应用程序首先记录到名为“MultipleFileBuilder”的记录器。然后,我使用 NLogHelper 类检索目标“DailiyFile”的内容。

希望这对某人有帮助。

(注意:我删除了“GetLogFileName”方法中文件是否存在的检查,因为在我的例子中文件不存在。)

I just did this today in C#. I followed the answer provided by arkmuetz here How to get path of current target file using NLog in runtime? to first get the filename of the Nlog target. I then read the file and copied the contents of the file to another Nlog target which emailed the log in the body of the message.

First I created an NlogHelper Class

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;
    }
}

Next I retrieved the file name in the constructor and stored it for later use.

_logLileName = NlogHelper.GetLogFileName("DailyFile");

For my purposes I created property that I later used to retrieve the contents of the log file.

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

Finally I added the contents of the file to the log to be emailed.

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

Here is my nLog.config file thought will help make things more clear.

<?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="[email protected]"
        to="[email protected]"/>
</targets>
<rules>
<logger name="MultipleFileBuilder" minlevel="Trace" writeTo="DailyFile" />
<logger name="ExcelBuilderService" minlevel="Debug" writeto="MyMailer" />
</rules>
</nlog>

My application first logs to the logger named 'MultipleFileBuilder'. I then use the NLogHelper class to retrieve the contents of the Target 'DailiyFile'.

Hope this helps someoneout.

(NOTE: I removed the checking to see if the file exists in the 'GetLogFileName' method because in my case file didn't exist.)

音盲 2024-12-26 06:58:32

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

I think you may use a combination of targets: default target + MethodCall and then send email manually or use Mail + Buffering to send a batch of records.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文