Search code examples
ipip-addressnloghost

NLog - Capture host's ip address


I am trying to capture the host / server's ipaddress within a .NET Core 2.0 application. The ${machinename} variable captures the server's name but how do you capture the server's IP address? The name is meaningless to my team but IP address is critical.


Solution

  • Lets say you have a static IP-address, then you can do this:

    var localIpAddress = LookupIpAddress(); // See https://stackoverflow.com/a/50386894/193178
    NLog.GlobalDiagnosticsContext.Set("LocalIpAddress", localIpAddress);
    

    Then you can use it target layout like this:

    layout="${longdate}|${level}|${logger}|${message}|${gdc=LocalIpAddress}"
    

    If your IP-address sometimes are changing, then you can setup a background-thread/timer to refresh the NLog-GDC-value.

    See also: https://github.com/NLog/NLog/wiki/Gdc-layout-renderer