简体   繁体   English

为什么我会使用 NLog 获得 FormatException?

[英]Why do I get FormatException with NLog?

I get the fllowing in the internal NLog log:我在内部 NLog 日志中得到以下信息:

2020-05-10 16:38:09.9251 Warn Error when formatting a message. Exception: System.FormatException: The input string had an incorrect format.
   vid System.Text.StringBuilder.FormatError()
   vid System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
   vid System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
   vid System.String.Format(IFormatProvider provider, String format, Object[] args)
   vid NLog.LogEventInfo.CalcFormattedMessage()

If fill the LogEventInfo like this:如果像这样填写 LogEventInfo:

var logEvent = new LogEventInfo();
                    logEvent.Level = logData.LogLevel.ToLogLevel();
                    logEvent.Message = JsonConvert.SerializeObject(logData, Formatting.Indented);
                    logEvent.Properties.Add("logdata", logData);
                    logEvent.Parameters = new object[1] { logData };
                    _genLogger.Log(logEvent);

The warning seems to come from when I set the Message to this:当我将 Message 设置为此时,警告似乎来自:

{
  "ComputerName": null,
  "LogLevel": 5,
  "LogId": null,
  "PersonId": null,
  "Text": "Communication Message",
  "TimeStamp": "2020-05-10T16:42:55.9456429+02:00",
  "ExceptionTyp": 7,
  "UserMessage": null,
  "RelatedObjectJsonString": "[\r\n  {\r\n    \"Address\": \"https://192.168.130.29:44476/MyApp5Service/Client\",\r\n    \"IsEmpty\": false,\r\n    \"IsFaulted\": false,\r\n    \"Action\": \"GetUserConfigurations\",\r\n    \"CallDirection\": 0,\r\n    \"EventTime\": \"2020-05-10T16:42:55.9406583+02:00\",\r\n    \"IsCallback\": false\r\n  }\r\n]",
  "SystemInformation": ""
}

What am I doing wrong?我究竟做错了什么?

Regards问候

The message is string-formatted or structured-formatted message.消息是字符串格式或结构化格式的消息。 The parameters are used for formatting the message.这些参数用于格式化消息。

Examples例子

String-formatted字符串格式

When all template holders are numeric (between the { and } ), the message is used as a string-formatted message.当所有模板持有者都是数字时(在{}之间),消息被用作字符串格式的消息。

logger.Info("Logon by user:{0} from ip_address:{1}", "Kenny", "127.0.0.1");

Where the first parameter is the message and the others the parameters其中第一个参数是消息,其他参数是参数

Structured format:结构化格式:

logger.Info("Logon by {user} from {ip_address}", "Kenny", "127.0.0.1"); // Logon by "Kenny" from "127.0.0.1"

Current issue目前的问题

So we're doing here something like:所以我们在这里做类似的事情:

string.Format("{
  "ComputerName": null,
  "LogLevel": 5,
  "LogId": null,
  "PersonId": null,
  "Text": "Communication Message",
  "TimeStamp": "2020-05-10T16:42:55.9456429+02:00",
  "ExceptionTyp": 7,
  "UserMessage": null,
  "RelatedObjectJsonString": "[\r\n  {\r\n    \"Address\": \"https://192.168.130.29:44476/MyApp5Service/Client\",\r\n    \"IsEmpty\": false,\r\n    \"IsFaulted\": false,\r\n    \"Action\": \"GetUserConfigurations\",\r\n    \"CallDirection\": 0,\r\n    \"EventTime\": \"2020-05-10T16:42:55.9406583+02:00\",\r\n    \"IsCallback\": false\r\n  }\r\n]",
  "SystemInformation": ""
}", logData);

Don't think that is what you need;)不要认为那是你需要的;)

Solution解决方案

I'm not sure if you need the data in your message.我不确定您是否需要消息中的数据。 So listed both options.所以列出了这两个选项。

There is no need to JSON convert the data yourself. JSON 不需要自己转换数据。 That could be done in the config.这可以在配置中完成。

Data in message消息中的数据

I would recommend to use structured logging here.我建议在这里使用结构化日志记录。

logger.Log(loglevel, "Message with {LogData}", logData);

You could render the logData as JSON as follows in your config:您可以在配置中将 logData 呈现为 JSON,如下所示:

${event-properties:item=LogData:jsonEncode=true}

See ${json-encode} and ${event-properties}${json-encode}${event-properties}

Note: you have some control how the message ( ${message} ) will be rendered, seeHow to use structured logging注意:您可以控制如何呈现消息( ${message} ),请参阅如何使用结构化日志记录

Data not in message消息中没有数据

Use the .WithProperty , which is syntactic sugar for the properties .使用.WithProperty ,它是属性的语法糖。

logger.WithProperty("LogData", logData).Log(loglevel, "Message without LogData");

Also here you could render the object as JSON with the ${event-properties:item=LogData:jsonEncode=true}同样在这里,您可以使用${event-properties:item=LogData:jsonEncode=true}将 object 渲染为 JSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将字符串转换为浮点数时,为什么会出现FormatException? - Why do I get a FormatException when converting a string to a float? 为什么我会收到FormatException? - Why am I getting FormatException on this? NLog-如何以编程方式获取调用方的类名和方法? - NLog - How do I get caller class name and method programmatically? 为什么我得到一个FormatException是未处理的错误? - Why am I getting a FormatException was unhandled error? C#当我使用TryParse时,为什么会收到“未处理的异常:System.FormatException:输入字符串的格式不正确。” - C# Why I get “Unhandled Exception: System.FormatException: Input string was not in a correct format.” when I use TryParse? 为什么try中的FormatException不会被catch中捕获? - Why does a FormatException within `try` not get caught in `catch`? 如何根据解决方案配置(发布或调试)让 NLog 输出到不同的目标? - How do I get NLog to output to different targets depending on the solution configuration (release or debug)? 我该如何格式化我的nLog布局 - how do i format my nLog layout 如何配置NLog写入数据库? - How do I configure NLog to write to a database? 我如何操纵NLog的堆栈级别? - How do i manipulate the stack level of NLog?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM