我正在使用NLog
来记录.net核心中的消息。
我在NLog
中添加了StartUp.cs
,如下所示:
loggerFactory.AddNLog();
要记录到文件,我使用以下方法:
logger.LogInformation("Message");
我想在我的消息中添加自定义NLog事件属性。但是LogInformation()不允许我传递它。我怎么能这样做?
答案 0 :(得分:5)
如果您想要自定义布局属性(NLog称它们为布局渲染器),您可以使用EventProperties Layout Renderer。您可以在代码中执行此操作:
var logger = LogManager.GetCurrentClassLogger();
var eventInfo = new LogEventInfo(LogLevel.Info, logger.Name, "Message");
eventInfo.Properties["CustomValue"] = "My custom string";
eventInfo.Properties["CustomDateTimeValue"] = new DateTime(2020, 10, 30, 11, 26, 50);
// You can also add them like this:
eventInfo.Properties.Add("CustomNumber", 42);
// Send to Log
logger.Log(eventInfo);
然后,您将能够在nlog.config
中添加这些(您构成的任何属性)<target>
<parameter name="@customtime" layout="${event-properties:CustomDateTimeValue:format=yyyy-MM-dd HH\:mm\:ss}" />
<parameter name="@customvalue" layout="${event-properties:item=CustomValue}" />
<parameter name="@customnumber" layout="${event-properties:item=CustomNumber}" />
</target>
将NLog与AspNetCore一起使用时,添加NLog.Web Package for ASP.NET Core会很有用,它会为您提供许多预定义的布局渲染器。您可以在Github页面上找到有关NLog.Web for AspNetCore的更多信息。
这个AspNetCore包将为您提供以下内容:
<parameter name="@UserName" layout="${aspnet-user-identity}" />
<parameter name="@MvcAction" layout="${aspnet-MVC-Action}" />
<parameter name="@Session" layout="${aspnet-session:Variable=User.Name:EvaluateAsNestedProperties=true}" />
... etc
您可以在NLog.Web.AspNetCore Github page上找到完整列表。
答案 1 :(得分:1)
逐步查找在.NET应用程序中设置Nlog的信息。
第1步: - 安装
从Nuget Manager安装版本4.0.0.0的NLog和NLog.Extended。
第2步: - WebConfig配置
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" throwExceptions="false" internalLogFile="D:\NLogErrors\log.txt">
<extensions>
<!-- load NLog.Extended to enable ASP.NET-specific functionality -->
<add assembly="NLog.Extended" />
</extensions>
<!--Define Various Log Targets like files, database or asp.net trace files-->
<targets>
<target name="oracle" xsi:type="Database" keepConnection="false" dbProvider="Oracle.DataAccess.Client.OracleConnection, Oracle.DataAccess, Version=4.121.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" connectionString="Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = "" )(PORT = 1521))(CONNECT_DATA =(SID = "")));User Id="";Password="";" commandText="INSERT INTO LOGTABLE (LOGMESSAGE,LOGLEVEL,LOGGERNAME,CREATEDDATETIME,SESSIONID,BROWSERDETAIL,REQUESTURL,ERRORMESSAGE,PRODUCERCODE,QUOTENO,CUSTOMER_IP_ADDRESS,SERVER_IP_ADDRESS) values(:LOGMESSAGE,:LOGLEVEL,:LOGGERNAME,:CREATEDDATETIME,:SESSIONID,:BROWSERDETAIL,:REQUESTURL,:ERRORMESSAGE,:PRODUCERCODE,:QUOTENO,:CUSTOMER_IP_ADDRESS,:SERVER_IP_ADDRESS)">
<parameter name="LOGMESSAGE" layout="${message}" />
<parameter name="LOGLEVEL" layout="${level:uppercase=true}" />
<parameter name="LOGGERNAME" layout="${logger}" />
<parameter name="CREATEDDATETIME" layout="${date}" />
<parameter name="SESSIONID" layout="${event-context:item=SessionId}" />
<parameter name="BROWSERDETAIL" layout="${event-context:item=BrowserDetail}" />
<parameter name="REQUESTURL" layout="${event-context:item=RequestUrl}" />
<parameter name="ERRORMESSAGE" layout="${event-context:item=ErrorMessage}" />
<parameter name="PRODUCERCODE" layout="${event-context:item=ProducerCode}" />
<parameter name="QUOTENO" layout="${event-context:item=QuoteNo}" />
<parameter name="CUSTOMER_IP_ADDRESS" layout="${event-context:item=CUSTOMER_IP_ADDRESS}"/>
<parameter name="SERVER_IP_ADDRESS" layout="${event-context:item=SERVER_IP_ADDRESS}"/>
</target>
<target xsi:type="Mail" name="Email" html="true" addNewLines="false" replaceNewlineWithBrTagInHtml="false" subject="Error Log" to="xyz@gmail.com" useSystemNetMailSettings="true" body="${event-context:item=EmailBody}">
</target>
</targets>
<rules>
<logger name="*" minlevel="trace" writeTo="oracle" />
</rules>
</nlog>
第3步: - Cs代码
public static class NLogManager
{
public static ILogger _logger =
NLog.LogManager.GetCurrentClassLogger();
public static void InfoLog(NLogData nLogData)
{
LogEventInfo theEvent = new LogEventInfo(LogLevel.Info, NLogManager._logger.Name, nLogData.Message);
SetLogEventInfo(theEvent, nLogData);
_logger.Log(theEvent);
}
}
private static void SetLogEventInfo(LogEventInfo theEvent, NLogData
nLogData)
{
theEvent.Properties["SessionId"] = nLogData.SessionId;
theEvent.Properties["BrowserDetail"] = nLogData.BrowserDetail;
theEvent.Properties["RequestUrl"] = nLogData.RequestUrl;
theEvent.Properties["ErrorMessage"] = nLogData.ErrorMessage;
theEvent.Properties["EmailBody"] = nLogData.EmailBody;
theEvent.Properties["ProducerCode"] = nLogData.ProducerCode;
theEvent.Properties["QuoteNo"] = nLogData.QuoteNo;
theEvent.Properties["CUSTOMER_IP_ADDRESS"] = nLogData.CustomerIPAddress;
theEvent.Properties["SERVER_IP_ADDRESS"] = nLogData.ServerIPAddress;
}
第4步: - 模型实体
public class NLogData
{
public string SessionId { get; set; }
public string Message { get; set; }
public string RequestUrl { get; set; }
public string BrowserDetail { get; set; }
public string Method { get; set; }
public string ErrorMessage { get; set; }
public string EmailBody { get; set; }
public string ProducerCode { get; set; }
public string QuoteNo { get; set; }
public string CustomerIPAddress { get; set; }
public string ServerIPAddress { get; set; }
}
步骤5: - 添加实施日志记录的下一行
NLogManager.TraceLog(NLogData nlogData);
- 创建上述方法接受的正确格式并相应地设置值
如果您有任何疑问,请发表评论或发邮件给我 ankitmori14@gmail.com