gpt4 book ai didi

c# - 从 Outlook 加载项调用时,NLog 不写入日志文件

转载 作者:行者123 更新时间:2023-11-30 20:33:07 26 4
gpt4 key购买 nike

我有一个用于 Outlook 的 C# 加载项(加载项 Express),我试图从中存储一些日志数据,但即使对记录器的调用没有失败,也没有创建日志文件。我在 Win 10 环境中使用 VS 2013。

我的NLog.Config文件(存放在文件夹OutlookAddin\bin\Debug中,与OutlookAddIn.dll.config在同一位置)如下:

<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="file" xsi:type="File"
layout="${longdate} ${logger} ${message}"
fileName="${specialfolder:ApplicationData}\FindAlike\NewMails.txt"
keepFileOpen="false"
encoding="iso-8859-2" />
</targets>

<rules>
<logger name="*" writeTo="file" />
</rules>

插件中的代码是声明:

public AddinModule()
{
Application.EnableVisualStyles();
InitializeComponent();
// Please add any initialization code to the AddinInitialize event handler
}

private ADXOutlookAppEvents adxOutlookEvents;
private DateTime LastReceivedDate = DateTime.Now;
private Timer mailCheckTimer;
public static RegistryKey SoftwareKey = Registry.CurrentUser.OpenSubKey("Software", true);
public static RegistryKey AppNameKey = SoftwareKey.CreateSubKey("FindAlike");
public static Logger logger = LogManager.GetCurrentClassLogger();

测试日志文件写入的例程是:

public static void TestNLog()
{
try
{
NLog.LogManager.ThrowExceptions = true;

logger.Info("test1");
logger.Warn("test2");
logger.Error("test3");

var fileTarget1 = (FileTarget)NLog.LogManager.Configuration.FindTargetByName("file");
var logEventInfo = new LogEventInfo { TimeStamp = DateTime.Now };
string fileName = fileTarget1.FileName.Render(logEventInfo);
if (!System.IO.File.Exists(fileName))
throw new Exception("Log file does not exist.");
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}

调用TestNLog时,虽然目标文件是正确的,但出现日志文件不存在的Message,说明配置文件读取成功。

当包含在可执行文件中时,相同的代码按预期工作。

最佳答案

除了@SimonKarvis 的回答之外,nlog.config 的位置可能很困难。这与单元测试相同。

我会推荐:

  1. 从 C# 创建配置,例如

     var target = new FileTarget
    {
    FileName = logfile,
    ReplaceFileContentsOnEachWrite = true,
    CreateDirs = createDirs
    };
    var config = new LoggingConfiguration();

    config.AddTarget("logfile", target);

    config.AddRuleForAllLevels(target);

    LogManager.Configuration = config;
  2. 或者从字符串加载配置:

    string configXml = "<nlog>...<nlog>";
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(configXml);
    var config = new XmlLoggingConfiguration(doc.DocumentElement, Environment.CurrentDirectory);
    LogManager.Configuration = config;
  3. 或者至少但不是最后,找到 nlog.config 的正确路径并将其“提供”给 NLog。

    var pathToNlogConfig = "c:\..";
    var config = new XmlLoggingConfiguration(pathToNlogConfig);
    LogManager.Configuration = config;

关于c# - 从 Outlook 加载项调用时,NLog 不写入日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40602775/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com