NLog进程信息的StartTime使用UTC时间
我使用XML配置,并希望把进程启动的日期和时间(以UTC表示)加入到文件名中。显然,到目前为止这是不可能的:
<variable name="procStartDate" value="${processinfo:property=StartTime:universalTime=true:format=yyyyMMdd" />
<variable name="procStartDateTime" value="${processinfo:property=StartTime:universalTime=true:format=yyyyMMdd-hhmmss" />
<variable name="logPathFilename" value="${basedir:dir=${procStartDate}:file=NLog file target ${procStartDateTime}}" />
会导致预期的异常,因为 universalTime 属性在 processinfo 中不可用:
NLogConfigurationException: ${processinfo} cannot assign unknown property 'universalTime='
除了为这部分添加编程配置外,还有没有其他解决办法?
解决方案
你可以使用 NLog GDC 来以你想要的任意格式输出Process-StartTime。NLog GDC的工作方式类似全局变量,可以在启动时进行赋值。示例:
NLog.GlobalDiagnosticsContext.Set("procStartDate", System.Diagnostics.Process GetCurrentProcess().StartTime.ToUniversalTime().ToString("yyyyMMdd"));
NLog.GlobalDiagnosticsContext.Set("procStartDateTime", System.Diagnostics.Process GetCurrentProcess().StartTime.ToUniversalTime().ToString("yyyyMMdd-hhmmss"));
如果在创建第一个NLog Logger之前为NLog GDC赋值,那么它们就可用于日志记录。示例:
<variable name="logPathFilename" value="${basedir}/${gdc:procStartDate}/NLog file target ${gdc:procStartDateTime}.log" />
P.S.发现让NLog依赖Process对象,实际上会引入大量依赖,增加AOT文件大小。
考虑在即将发布的NLog v6.2中进行一个小幅的破坏性变更,因为.NET v11已经优化了Process对象,因此可以在不引入整个依赖链的情况下访问Process-Name:
这意味着NLog布局渲染器 ${processinfo} 将被标记为过时,其输出将被“调整”为不再依赖Process对象。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。