question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Nlog | JsonLayout | includeAllProperties='true' => How can i change datetime format in object?

See original GitHub issue

Hi!

I have a little problem about DateTime format in my class?

NLog version: 4.6.7

Platform: .Net 4.6.1

Current NLog config

<target name="ijson" xsi:type="File" fileName="${basedir}/logs/Trace/i_${date:format=yyyyMMddHH}.log" >
  <layout type="JsonLayout">
	<attribute name="Time" layout="${date:format=O}" />
	<attribute name="Level" layout="${level:upperCase=true}"/>
	<attribute name="Properties" encode="false" >
	  <layout type='JsonLayout' includeAllProperties="true" excludeProperties="EventId_Id,EventId_Name,EventId"   maxRecursionLimit="5"/>
	</attribute>
  </layout>
</target>

My Object Class

    public class ActivityLogModel
    {
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }
        public double ProcessTime { get; set; }
    }

My Code

public static void WriteNLog(object obj)
{
	Logger _logger = NLog.LogManager.GetCurrentClassLogger();
	_logger.Info("{Object}", obj);
}

Output

{
  "Time": "2019-08-29T11:42:33.9779998+07:00",
  "Level": "INFO",
  "Properties": {
    "Object": {
      "ActivityLog": {
        "StartTime": "2019-08-29T04:41:15.9925922Z",
        "EndTime": "2019-08-29T04:41:16.8197183Z",
        "ProcessTime": 827.1261
      }
    }
  }
}

Can i change DateTime format in object like <attribute name="Time" layout="${date:format=O}" /> ?

Thanks you

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
artzlitecommented, Sep 6, 2019

Thanks for replying. Finally , My code is

public class NLogJsonSerializer : NLog.IJsonConverter
    {
        readonly JsonSerializerSettings _settings;

        public NLogJsonSerializer()
        {
            _settings = new JsonSerializerSettings
            {
                Formatting = Formatting.None,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                DateFormatString = "O"
            };
        }

        public bool SerializeObject(object value, StringBuilder builder)
        {
            try
            {
                var jsonSerializer = JsonSerializer.CreateDefault(_settings);
                var sw = new System.IO.StringWriter(builder, System.Globalization.CultureInfo.InvariantCulture);
                using (var jsonWriter = new JsonTextWriter(sw))
                {
                    jsonWriter.Formatting = jsonSerializer.Formatting;
                    jsonSerializer.Serialize(jsonWriter, value, null);
                }
            }
            catch (Exception e)
            {
                NLog.Common.InternalLogger.Error(e, "Error when custom JSON serialization");
                return false;
            }
            return true;
        }
    }

And When i use

public static void WriteNLog(object obj)
        {
            //var oldJsonConverter = NLog.Config.ConfigurationItemFactory.Default.JsonConverter;
            var newConverter = new NLogJsonSerializer();
            NLog.Config.ConfigurationItemFactory.Default.JsonConverter = newConverter;
            Logger _logger = NLog.LogManager.GetCurrentClassLogger();
            _logger.Info("{Object}", obj);
        }

Thanks for this solution!!

1reaction
snakefootcommented, Sep 1, 2019

If you override the IJsonConverter before loading NLog-config or creating NLog-Logger, then this should work:

internal class JsonLogModelSerializer : NLog.IJsonConverter
{
    private NLog.IJsonConverter _originalConverter;
    public JsonLogModelSerializer(NLog.IJsonConverter originalConverter)
    {
        _originalConverter = originalConverter;
    }

    /// <summary>Serialization of an object into JSON format.</summary>
    /// <param name="value">The object to serialize to JSON.</param>
    /// <param name="builder">Output destination.</param>
    /// <returns>Serialize succeeded (true/false)</returns>
    public bool SerializeObject(object value, System.Text.StringBuilder builder)
    {
        if (value is ActivityLogModel logModel)
        {
            builder.Append("\"StartTime\": \"").Append(logModel.StartTime.ToString("O")).Append("\"");
            builder.Append("\"EndTime\": \"").Append(logModel.EndTime.ToString("O")).Append("\"");
            builder.Append("\"ProcessTime\":  ").Append(logModel.ProcessTime.ToString(System.Globalization.CultureInfo.InvariantCulture))
            return true;
        }

        return _originalConverter.SerializeObject(value, builder);
    }
}
var oldJsonConverter = NLog.Config.ConfigurationItemFactory.Default.JsonConverter;
var newConverter = new JsonLogModelSerializer(oldJsonConverter);
NLog.Config.ConfigurationItemFactory.Default.JsonConverter = newConverter;

You can also replace it completely using Json.Net (and inject your own datetime-format).

https://github.com/NLog/NLog/wiki/How-to-use-structured-logging#i-like-to-use-jsonnet-for-creating-json

Read more comments on GitHub >

github_iconTop Results From Across the Web

NLog time formatting
3 Answers. According to the NLog documentation, you can use C# DateTime format string. Another alternative to the format suggested by harriyott ...
Read more >
Config options for NLog's configuration
Date and time. ${date} - Current date and time. ${longdate} - The date and time in a long, sortable format `yyyy-MM-dd HH:mm:ss.ffff`.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found