AWS CloudWatch 日志记录在一台机器上工作,而不是另一台机器

时间:2021-03-20 02:39:32

标签: c# amazon-cloudwatch nlog

我有 2 个 EC2 Windows 10 实例。使用 C# 和 AWSSDK.CloudWatchLogs,我可以从其中之一写入 AWS CloudWatch,但不能从另一个写入。我可以用下面的代码复制这个:

C# 代码:

using System;

namespace AllPurposeDuck
{
    class Program
    {
        private static Logger _log = LogManager.GetCurrentClassLogger();
        static void Main(string[] args)
        {
            try
            {
                _log.Info("Quack!");
                _log.Debug("Quack!!");
                _log.Trace("Quack!!!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>

  <nlog throwExceptions="true"
        internalLogFile="c:\temp\allpurposeducklog.txt"
        internalLogLevel="Info"
        xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
      <target name="console" xsi:type="Console" layout="${longdate} | ${level} | ${machinename}| ${message}" />
      <target name="aws" xsi:type="AWSTarget" logGroup="Ducks_and_stuff" region="us-west-2" layout="${machinename} ${longdate} | ${level} | ${message}" />
    </targets>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="console, aws" />
    </rules>
  </nlog>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
  </startup>
</configuration>

在以其他方式静默失败的机器上,我注意到短暂的停顿并在我的 c:\temp\allpurposeducklog.txt 本地日志文件中看到以下警告:

2021-03-20 01:36:40.7679 Info Shutting down logging...
2021-03-20 01:36:42.2809 Warn Target flush timeout. One or more targets did not complete flush operation, skipping target close.
2021-03-20 01:36:42.2809 Info Logger has been shut down.

另一台机器高兴地对着 CloudWatch 嘎嘎叫(都嘎嘎对着控制台)。

故障机器与工作机器在同一个 VPC 中,具有相同的 IAM 角色、可用区和安全组。两台机器都与 CloudWatch 代理一起正常工作,该代理监控 Windows 内存并在内存过低时触发警报。

我很难进一步缩小范围。想法? AWS 中是否有可能记录失败原因的地方?谢谢。

1 个答案:

答案 0 :(得分:2)

由于程序在日志记录后很快退出,NLog 可能仍然忙于写入日志。如果目标使用异步日志记录,NLog 需要知道它应该等待写入。

总是建议在程序退出前留出一些时间。在 Main 末尾添加:

LogManager.Shutdown();

这将使 NLog 最多 15 秒。

如果时间不够,您可以先刷新并等待,例如最多 30 秒。

LogManager.Flush(TimeSpan.FromSeconds(30));
LogManager.Shutdown();

另见https://github.com/NLog/NLog/wiki/Logging-troubleshooting

相关问题