Skip to content

Latest commit

 

History

History
785 lines (595 loc) · 40.4 KB

net-configure-logs-context-all.mdx

File metadata and controls

785 lines (595 loc) · 40.4 KB
title tags metaDescription redirects freshnessValidatedDate
.NET agent logs in context
Logs
Enable log management in New Relic
Configure logs in context
For apps monitored by .NET, learn how to link log data with related data across the rest of the New Relic platform.
/docs/logs/new-relic-logs/enable-logs-context/enable-logs-context-net
/docs/logs/enable-logs/logs-context-net/configure-logs-context-net
/docs/logs/enable-log-monitoring-new-relic/logs-context-net/configure-logs-context-net
/docs/logs/enable-log-management-new-relic/logs-context-net/net-configure-log4net
/docs/logs/enable-new-relic-logs/logs-context-net/net-configure-log4net
/docs/logs/enable-log-monitoring-new-relic/logs-context-net/net-configure-log4net
/docs/logs/enable-log-management-new-relic/logs-context-net/net-configure-nlog
/docs/logs/enable-new-relic-logs/logs-context-net/net-configure-nlog
/docs/logs/enable-log-monitoring-new-relic/logs-context-net/net-configure-nlog
/docs/logs/enable-log-management-new-relic/logs-context-net/net-configure-serilog
/docs/logs/new-relic-logs/enable-logs-context/enable-logs-context-net-serilog
/docs/logs/enable-logs/logs-context-net/net-configure-serilog
/docs/logs/enable-log-monitoring-new-relic/logs-context-net/net-configure-serilog
/docs/logs/enable-log-management-new-relic/configure-logs-context/net-configure-logs-context-all
never

import logsDotnetLogsinContext from 'images/logs_diagram_dotnet-logs-in-context.webp'

import logsDotnetLogsinContextSerilog from 'images/logs_diagram_dotnet-logs-in-context-serilog.webp'

With our .NET agent, you can get logs in context, which lets you see your app logs in the context of your other New Relic data. For general information on this feature, see APM logs in context.

Got lots of .Net logs? Check out our [tutorial on how to optimize and manage them](/docs/tutorial-large-logs/get-started-managing-large-logs/).

Automatic logs in context options [#automatic]

You have three options to configure logs in context to send your app's logs and linking metadata automatically to New Relic. Supported frameworks for automatic logs in context using in agent forwarding include:

<table>
  <thead>
    <tr>
      <th style={{ width: "200px" }}>
        Frameworks
      </th>

      <th>
        Minimium framework version
      </th>

      <th>
        Minimium agent version
      </th>

    </tr>
  </thead>

  <tbody>
    <tr>
      <td>
        Log4Net
      </td>
      <td>
        For .NET Framework: v1.2.10

        For .NET Core: v2.0.10
      </td>
      <td>
        v9.7.0
      </td>
    </tr>

    <tr>
      <td>
        Serilog
      </td>
      <td>
        For .NET Framework: v2.0.0

        For .NET Core: v2.5.0
      </td>
      <td>
        v9.7.0
      </td>
    </tr>

    <tr>
      <td>
        NLog
      </td>
      <td>
        For .NET Framework: v4.1.0

        For .NET Core: v4.5.0
      </td>
      <td>
        v9.7.0
      </td>
    </tr>

    <tr>
      <td>
        Microsoft.Extensions.Logging
      </td>
      <td>
        v3.0.0
      </td>
      <td>
        For .NET Framework: Agent v9.7.0

        For .NET Core: Agent v10.0.0
      </td>
    </tr>
  </tbody>
</table>
Many versions of Sitecore use Sitecore.Logging, which is based off a fork of log4net, but independent. Support for this library was added in version 10.14.0 of the .NET Agent.

<Collapser id="1-agent" title="Option 1 (simplest): Let the agent forward your log's messages."

This is the simplest approach, and it's a great choice for developers who may not have the access or interest in setting up a log forwarder, or for accounts that want to see the power of logs and other linking metadata in context of their apps, without a lot of overhead.

Using this option, your logs include span.id, trace.id, hostname, entity.guid, and entity.name. Learn about log forwarding limitations.

All you need to do is install an agent version with log forwarding capabilities (.NET agent 9.7.0 or higher). If forwarding is disabled, you can enable it by adding the following to your agent configuration file:

<applicationLogging enabled="true">
  <forwarding enabled="true" maxSamplesStored="10000" />
  <localDecorating enabled="false" />
</applicationLogging>

Environment variables:

NEW_RELIC_APPLICATION_LOGGING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_MAX_SAMPLES_STORED=10000
NEW_RELIC_APPLICATION_LOGGING_LOCAL_DECORATING_ENABLED=false
The environment variable value, if present, takes precedence over the config file value.

Beginning with agent version 9.8.0, this feature is enabled by default.

Beginning with agent version 10.4.0, the agent also supports capturing and forwarding context data (custom attributes) from log events. This sub-feature is disabled by default. To enable, use the following configuration:

<applicationLogging enabled="true">
  <forwarding enabled="true" maxSamplesStored="10000">
    <contextData enabled="true" include="" exclude="" />
  </forwarding>
  <localDecorating enabled="false" />
</applicationLogging>

Environment variables:

NEW_RELIC_APPLICATION_LOGGING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_CONTEXT_DATA_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_MAX_SAMPLES_STORED=10000
NEW_RELIC_APPLICATION_LOGGING_LOCAL_DECORATING_ENABLED=false

New Relic uses context data prefixed with "context". For example, a custom log attribute named myKey with value myValue for New Relic is context.myKey : myValue.

The .NET logging libraries we instrument typically store context data key-value pairs on each log event as a Dictionary<string,object>. To convert the values to strings before being sent to New Relic, we first attempt to use Newtonsoft.Json.JsonConvert.SerializeObject. If that fails, we attempt to call .ToString() on the object; as a last resort we will send the type name.

You can filter context data using the include and exclude configuration options. These are comma-separated lists of attribute names. The default values for both are empty strings; an empty include field means "include everything". These include/exclude options follow the same rules as other agent attribute configuration options.

For example, to include all attributes that start with "a" except "apple", and exclude all attributes that start with "b" except "banana", use the following configuration:

<applicationLogging enabled="true">
  <forwarding enabled="true" maxSamplesStored="10000">
    <contextData enabled="true" include="a*, banana" exclude="b*, apple" />
  </forwarding>
  <localDecorating enabled="false" />
</applicationLogging>

Environment variables:

NEW_RELIC_APPLICATION_LOGGING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_CONTEXT_DATA_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_CONTEXT_DATA_INCLUDE="a*, banana"
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_CONTEXT_DATA_EXCLUDE="b*, apple"
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_MAX_SAMPLES_STORED=10000
NEW_RELIC_APPLICATION_LOGGING_LOCAL_DECORATING_ENABLED=false

Optional adjustments:

Once log forwarding is enabled, you also have control over the maximum number of logs sent to New Relic every minute. The default value is 10,000. If more than 10,000 logs are received in a 60-second window, your logs will begin to be sampled.

Set it to a higher number to receive more logs. Set it to a lower number to receive fewer logs. Any integer is valid.

<applicationLogging enabled="true">
  <forwarding enabled="true" maxSamplesStored="10000" />
  <localDecorating enabled="false" />
</applicationLogging>

Environment variables:

NEW_RELIC_APPLICATION_LOGGING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_MAX_SAMPLES_STORED=10000
NEW_RELIC_APPLICATION_LOGGING_LOCAL_DECORATING_ENABLED=false
The environment variable value, if present, takes precedence over the config file value.

If you have an existing log forwarding solution and are updating your agent to use automatic logs in context, be sure to disable your manual log forwarder. Otherwise, your app will be sending double log lines. Depending on your account, this could result in double billing. For more information, follow the procedures to disable your specific log forwarder.

<Collapser id="2-decorate" title="Option 2: Let the agent decorate your logs."

Already have a log forwarder you like? We've got you covered! Language agents can decorate your logs with the linking metadata needed to provide access to automatic logs-in-context features.

This option should not be used with in-agent forwarding. Using an external log forwarder to send logs to New Relic while in-agent forwarding is enabled will cause your logs to be sent up twice to New Relic. Depending on your account, this may result in double billing.

Local log decoration for the .NET agent does not directly alter log messages. Your logging framework configuration will need to be updated to write out the `NR-LINKING` token in messages. For JSON output in log4net and Serilog, additional configuration or code will be required.
  1. If you want to use this option, make sure you have the in-agent forwarding configuration option disabled.

  2. Enable log decorating in your configuration, then relaunch the agent to start decorating your logs.

<applicationLogging enabled="true">
  <forwarding enabled="false" />
  <localDecorating enabled="true" />
</applicationLogging>

Environment variables:

NEW_RELIC_APPLICATION_LOGGING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_ENABLED=false
NEW_RELIC_APPLICATION_LOGGING_LOCAL_DECORATING_ENABLED=true
The environment variable value, if present, takes precedence over the config file value.

Our decorator adds five attributes to every log message (plain text): entity.guid, entity.name, hostname, trace.id, and span.id. Example:

This is my log message. NR-LINKING|{entity.guid}|{hostname}|{trace.id}|{span.id}|{entity.name}
For JSON, the `NR-LINKING` data must be in the `message` property.

Some attributes may be empty if the log occurred outside a transaction or if they are not applicable to your application's context. We recommend this option over the manual process to use a decorating formatter.

The key used to read out the `NR-LINKING` token from a logging framework is `NR_LINKING` not `NR-LINKING` in order to support logging frameworks that do not allow hyphens in key names.

log4net configuration

For log4net, the .NET agent stores the NR-LINKING token as a property called NR_LINKING in the log event object. The following common layout examples demonstrate how to configure log4net to write out out the NR-LINKING token. Other layouts are supported, but not listed below. SimpleLayout is not supported since it cannot be altered.

PatternLayout/DynamicPatternLayout: Update the conversionPattern to include the NR_LINKING property at the end of the line.

<layout type="log4net.Layout.PatternLayout">
  <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message %property{NR_LINKING}%newline %exception" />
</layout>

log4net.Ext.Json: Update the layout to include a member called NR_LINKING in the message JSON property.

log4net.Appender.AdoNetAppender: This appender has a slightly different configuration than other layouts. You will need to update the message parameter to include the metadata. The following example demonstrates this using a PatternLayout.

<parameter>
  <parameterName value="@message" />
  <dbType value="String" />
  <size value="4000" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%message %property{NR_LINKING}" />
  </layout>
</parameter>

Serilog configuration

For Serilog, the .NET agent stores the NR-LINKING token as a property called NR_LINKING in the log event object. The following common formatter and sink examples demonstrate how to configure Serilog to write out out the NR-LINKING token. Other sinks and formatters are supported, but not listed below.

Plain text using an outputTemplate: Update the outputTemplate to include the NR_LINKING property at the end of the line.

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
    .Enrich.FromLogContext()
    .WriteTo.File(
        path: @"plaintext_log.txt",
        fileSizeLimitBytes: 1_000_000,
        rollOnFileSizeLimit: true,
        shared: true,
        flushToDiskInterval: TimeSpan.FromSeconds(1),
        outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj} {NR_LINKING} {NewLine}{Exception}"
    )
    .CreateLogger();

JSON Formatter with automatic property output: The default JsonFormatter will not write the NR_LINKING metadata to the message property; instead, it writes each property to its own JSON object. You will need to create a custom JSON formatter to write the NR_LINKING data to the end of the message property before logs in context will work.

Microsoft.Extensions.Logging configuration

For Microsoft.Extensions.Logging, the .NET agent stores the NR-LINKING token with the message in a newly created a Scope. Since Microsoft.Extensions.Logging relies on other frameworks for output, please see either the log4net or Serilog configuration above for details.

NLog configuration

For NLog, the .NET agent is able to automatically append the NR-LINKING token directly to the end of the message so no additional configuration is required.

<Collapser id="3-old-formatter" title="Option 3: Use the manual process to forward and decorate logs."

Before language agents had the ability to forward and decorate logs, you could enable logs in context by updating your application to send linking metadata.

This option is still supported, but is no longer encouraged. For instructions to use this approach, see Manual logs in context option.

Also, this method requires that you install a log forwarder before enabling logs in context. If you do not have a log forwarder, the New Relic UI will prompt you to use our infrastructure agent.

If you decide to use your existing log forwarding solution and later decide to update your agent to use automatic logs in context, be sure to disable your manual log forwarder. Otherwise, your app will be sending double log lines. Depending on your account, this could result in double billing. For more information, follow the procedures to disable your specific log forwarder.

Secure your data [#obfuscation]

Your logs may include sensitive information protected by HIPAA or other compliance protocols. By default we obfuscate number patterns that appear to be for items such as credit cards or Social Security numbers, but you may need to hash or mask additional information.

For more information, see obfuscation expressions and rules. You can hash or mask your log data by using the New Relic UI or by using NerdGraph, our GraphQL API.

Explore your data [#view-ui]

To make the most of your logging data:

  • On the APM Summary page, click your Web transaction time chart to view logs associated with a specific point in time.
  • Check your app's Errors inbox to view the logs associated with your errors.
  • Use distributed tracing to see the logs associated with individual traces.
  • Explore more logging data across your platform with our logs UI.
  • Set up alerts based on log output and severity.
  • Query your data using our specialized UI for logs data, and create dashboards with the results.

Troubleshooting tips [#troubleshooting]

Typically your logs will start to appear less than a minute after you enable APM logs in context. Check your app's Triage > Logs section. You will also start seeing log patterns related to the error there.

If you don't see any logs for errors or traces, there may not be any for your app. Try refreshing the UI page, or change the selected time period.

Disable automatic logging [#disable-automatic]

APM logs in context automatically forwards agent log data and is enabled by default. This can have a negative impact on your security, compliance, billing, or system performance. For more information, or if you need to adjust the default setting, follow the procedures to disable automatic logging.

Manual logs in context option [#enable-logs-net]

If you need to use the manual process to set up logs in context for .NET, follow these steps:

  1. Make sure you have already set up logging in New Relic. This includes configuring a supported log forwarder that collects your application logs and extends the metadata that is forwarded to New Relic.
  2. Install or update to the latest .NET agent version, and enable distributed tracing. Use .NET agent version 8.21 or higher and the New Relic .NET agent API version 8.21 or higher for logs in context.
  3. Install or update to Microsoft .NET Framework 4.5 or higher or .NET Core 2.0 or higher.
  4. Install and configure any of the following logging extensions to enrich your log data, including:
  1. Check your log data in the New Relic UI.

Configure log4net extension [#log4net]

You can use the Apache log4net version 2.0.8 or higher extension to link your log data with related data across the rest of the New Relic platform.

The following diagram illustrates the flow of log messages through Apache log4net, highlighting specific components of the New Relic log4net extension. Many log forwarders are available. This example uses [Fluentd](https://www.fluentd.org/).
<img
  title="log4net extension for logs in context with New Relic's .NET agent"
  alt="Logs In Context - Log4Net"
  src={logsDotnetLogsinContext}
/>

<DoNotTranslate>**Appender:**</DoNotTranslate> The `NewRelicAppender` adds contextual information from the .NET agent (using the API) to the log events generated by the application. This contextual information, known as linking metadata, is used by New Relic to link log messages to the transactions and spans from which they were created. This appender will pass the enriched log events to downstream appenders for further processing.

Since the `NewRelicAppender` is `ForwardingAppender` type, it needs to be the first appender in the chain. It also requires another appender that can write to an actual output destination as its child in order to work.

<DoNotTranslate>**Layout:**</DoNotTranslate> The `NewRelicLayout` formats the enriched log events into the JSON format expected by New Relic. The appender, which this layout is assigned to, instructs log4net to output the JSON to a file in the location that the log forwarder expects.

<DoNotTranslate>**Log Forwarder**</DoNotTranslate>: The log forwarder monitors an output folder and incrementally sends the properly formatted and enriched log information to the New Relic logging endpoint.

<Collapser id="config-log4net" title="log4net 2.0.8 or higher configuration"

Log4net uses `appender` and `layout` to store and format log messages. [`NewRelicAppender`](https://github.com/newrelic/newrelic-logenricher-dotnet/tree/master/src/Log4Net) enriches log messages with contextual information from the New Relic .NET agent if it is attached to your application. The appender passes enriched log messages to downstream appenders to handle specific use cases for log messages.

For more information about logging with log4net, see the Apache log4net [Getting started](https://logging.apache.org/log4net/) documentation.

To configure logs in context with the log4net extension:

1. Using the Visual Studio [NuGet Package Manager](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-visual-studio), locate and install the [`NewRelic.LogEnrichers.Log4Net`](https://www.nuget.org/packages/NewRelic.LogEnrichers.Log4Net/) package.

2. In your log4net configuration file, update your logging configuration to use the `NewRelicAppender` as the first level appender, and reference your existing appenders as its children. Also replace the layout of the appender that writes log messages to an output destination with the `NewRelicLayout`.

  The following log4net configuration example enriches log events with New Relic linking metadata. In addition to the existing log files, it outputs new log files in a specific JSON format at `C:\logs\log4netExample.log.json` for consumption by the log forwarder:

  ```xml
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="NewRelicAppender" />
    </root>

    <appender name="NewRelicAppender" type="NewRelic.LogEnrichers.Log4Net.NewRelicAppender, NewRelic.LogEnrichers.Log4Net" >
      <threshold value="ALL"/>
      <appender-ref ref="FileAppender" />
    </appender>

    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="C:\logs\log4netExample.log.json" />
      <param name="AppendToFile" value="true" />
      <layout type="NewRelic.LogEnrichers.Log4Net.NewRelicLayout, NewRelic.LogEnrichers.Log4Net">
      </layout>
    </appender>
  </log4net>
  ```

  After you configure the log4net extension and update your logging file, you can configure your extension to send data to New Relic. There are [several options](/docs/logs/forward-logs/enable-log-management-new-relic/#log-forwarding) for forwarding your logs. Here is an example configuration using the infrastructure agent for logs in context:

  ```yml
  logs:
    - name: application-log
      file: C:\logs\log4netExample.log.json # Path to a single log file
  ```

  [Documentation for using the infrastructure agent forwarder](/docs/logs/forward-logs/forward-your-logs-using-infrastructure-agent/#file)

Configure NLog extension [#nlog]

You can use our NLog 4.5 or higher extension to link to your log data with related data across the rest of the New Relic platform.

The [New Relic NLog extension](https://github.com/newrelic/newrelic-logenricher-dotnet) provides a `NewRelicJsonLayout` that formats a log event in the way required by the New Relic logging endpoint. Next, it adds contextual information from the .NET agent when attached to your application. Then, a target can be configured to write logging data to an output folder. The log forwarder can monitor this folder and incrementally send log information to New Relic.
The following diagram illustrates the flow of log messages through NLog, highlighting specific components of the New Relic NLog extension.

<img
  title="NLog extension for logs in context with New Relic's .NET agent"
  alt="Logs In Context - NLog"
  src={logsDotnetLogsinContext}
/>

<DoNotTranslate>**New Relic JSON Layout**</DoNotTranslate>: The `NewRelicJsonLayout` adds contextual information from the .NET agent (using the API) to the log events generated by the application, and outputs log messages in the JSON format expected by New Relic. This contextual information, known as linking metadata, is used by New Relic to link log messages to the transactions and spans where they were created.

Since the `NewRelicAppender` is `ForwardingAppender` type, it needs to be the first appender in the chain. It also requires another appender that can write to an actual output destination as its child in order to work.

<DoNotTranslate>**File Target**</DoNotTranslate>: A `FileTarget` defines a file on disk where log messages are written. Adding the `NewRelicJsonLayout` to that target allows the output to be formatted correctly for forwarding to New Relic.

<DoNotTranslate>**Log Forwarder**</DoNotTranslate>: The log forwarder is configured to send the properly formatted and enriched log data from the `FileTarget` output to the New Relic logging endpoint.

For more information about logging with NLog, see the [nlog-project.org documentation](https://nlog-project.org/download/).

<Collapser id="config-nlog" title="NLog 4.5 or higher configuration"

Use our [NLog 4.5 or higher](https://nlog-project.org/) extension to link to your log data with related data across the rest of the New Relic platform.

1. Using the Visual Studio [NuGet Package Manager](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-visual-studio), locate and install the [`NewRelic.LogEnrichers.NLog`](https://www.nuget.org/packages/NewRelic.LogEnrichers.NLog/) package.
2. In your application code, update your logging configuration to add the `NewRelicJsonLayout` and decide if you want to collect MappedDiagnosticsContext (<DoNotTranslate>**MDC**</DoNotTranslate>) or the MappedDiagnosticsLogicalContext (<DoNotTranslate>**MDLC**</DoNotTranslate>) data.

   The following configuration examples result in new JSON files that are written to disk. Some of these [configuration options](https://github.com/nlog/NLog/wiki/File-target) may be useful for managing the amount of disk space used and/or the performance of the target.

* `archiveAboveSize`
* `maxArchiveFiles`
* `bufferSize`
* `enableArchiveFileCompression`
* `autoFlush`
* `concurrentWrites`

  Although the [NLog AsyncWrapper Target](https://github.com/nlog/NLog/wiki/AsyncWrapper-target) is not required, it may help improve performance by performing formatting and output of log files on a different thread.

  <DoNotTranslate>**Don't collect MDC or the MDLC data (default):**</DoNotTranslate>

  The following code example enriches log events with New Relic linking metadata, but not with MDC or the MDLC data. In addition to the existing log files, it outputs new log files in a specific JSON format at `C:\logs\NLogExample.log.json` for consumption by the log forwarder:

  ```cs
  var loggerConfig = new LoggingConfiguration();
  var newRelicFileTarget = new FileTarget("NewRelicFileTarget");
  newRelicFileTarget.Layout = new NewRelicJsonLayout();
  newRelicFileTarget.FileName = "C:\logs\NLogExample.json";
  loggerConfig.AddTarget(newRelicFileTarget);
  loggerConfig.AddRuleForAllLevels("NewRelicFileTarget");
  LogManager.Configuration = loggerConfig;
  var logger = LogManager.GetLogger("Example");
  ```

  <DoNotTranslate>**Collect MDC or the MDLC data:**</DoNotTranslate>

  If your application uses the MDC or the MDLC, you can configure the `NewRelicJsonLayout` to include items in those collections. The following code example adds the additional configuration to enable collecting MDC and MDLC data. As in the previous example, it outputs new log files in a specific JSON format at `C:\logs\NLogExample.log.json` for consumption by the log forwarder:

  ```cs
  var loggerConfig = new LoggingConfiguration();
  var newRelicFileTarget = new FileTarget("NewRelicFileTarget");
  var newRelicLayout = new NewRelicJsonLayout
  {
      IncludeScopeProperties = true
  };

  newRelicFileTarget.Layout = newRelicLayout;
  newRelicFileTarget.FileName = @"C:\logs\NLogExample.json";
  loggerConfig.AddTarget(newRelicFileTarget);
  loggerConfig.AddRuleForAllLevels("NewRelicFileTarget");
  LogManager.Configuration = loggerConfig;
  var logger = LogManager.GetLogger("Example");
  ```

  Once you have configured the NLog extension and updated your logging file, you can configure your extension to send data to New Relic. There are [several options](/docs/logs/forward-logs/enable-log-management-new-relic/#log-forwarding) for forwarding your logs. Here is an example configuration using the infrastructure agent for logs in context:

  ```yml
  logs:
    - name: application-log
      file: C:\logs\log4netExample.log.json # Path to a single log file
  ```

  [Documentation for using the infrastructure agent forwarder](/docs/logs/forward-logs/forward-your-logs-using-infrastructure-agent/#file)

<Collapser id="nlog-file" title="NLog file-based configuration"

You can also configure the New Relic NLog extension with file-based configuration providers. The folowing example code creates a logger based on settings contained in an `App.config` file.

<DoNotTranslate>**Instantiating Logger using `.config` file**</DoNotTranslate>

```cs
var logger = LogManager.GetLogger("NewRelicLog");
logger.Info("Hello, New Relic!");
```

<DoNotTranslate>**Sample `App.config` file**</DoNotTranslate>

```xml
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <extensions>
      <add assembly="NewRelic.LogEnrichers.NLog" />
    </extensions>
    <targets>
      <target name="NewRelicLogFile" xsi:type="File" fileName="C:/path/to/NewRelicLog.json">
        <layout xsi:type="newrelic-jsonlayout">
        </layout>
      </target>
    </targets>
    <rules>
      <logger name="NewRelicLog" minlevel="Info" writeTo="newRelicLogFile" />
    </rules>
  </nlog>
</configuration>
```

Configure Serilog 2.5 or higher extension [#serilog]

You can use our Serilog extension to link to your log data with related data across the rest of the New Relic platform. This requires:

Serilog is a structured logging framework that records log messages from your application and creates a `LogEvent` to store the message data. Using [Enrichers](https://github.com/serilog/serilog/wiki/Enrichment), you can add additional information to the log events. [Sinks](https://github.com/serilog/serilog/wiki/Provided-Sinks) and [Formatters](https://github.com/serilog/serilog/wiki/Formatting-Output) allow you to format and output those log events for downstream consumption and viewing.
The following diagram illustrates the flow of log messages through Serilog, highlighting specific components of the New Relic Serilog extension. Many log forwarders are available. This example uses [Fluentd](https://www.fluentd.org/).

<img
  title="Serilog extension for logs in context with New Relic's .NET agent"
  alt="Logs-in-context Serilog"
  src={logsDotnetLogsinContextSerilog}
/>

<DoNotTranslate>**New Relic Enricher**</DoNotTranslate>: The `NewRelicEnricher` adds contextual information from the .NET agent (using the API) to the log events generated by the application. This contextual information, called linking metadata, is used by New Relic to link log messages to the transactions and spans where they were created.

<DoNotTranslate>**New Relic Formatter**</DoNotTranslate>: The `NewRelicFormatter` translates enriched log events into the JSON format expected by New Relic. A sink instructs Serilog to output the JSON to a file in the location that the log forwarder expects.

<DoNotTranslate>**New Relic Log Forwarder**</DoNotTranslate>: The log forwarder is configured to send the properly formatted and enriched log data from the `FileTarget` output to the New Relic logging endpoint.

For more information about Serilog log events, see the [Serilog documentation on GitHub](https://github.com/serilog/serilog/wiki/Getting-Started).

<Collapser id="config-serilog" title="Serilog 2.5 or higher configuration"

To configure logs in context with the Serilog extension:

1. Use the Visual Studio [NuGet Package Manager](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-visual-studio) to locate and install the [`NewRelic.LogEnrichers.Serilog`](https://www.nuget.org/packages/NewRelic.LogEnrichers.Serilog) package.

2. In your application code, update your logging configuration to add the `NewRelicEnricher` and `NewRelicFormatter`.

The following code example enriches log events with New Relic linking metadata. In addition to the existing log files, it outputs new log files in a specific JSON format at `C:\logs\SerilogExample.log.json` for consumption by the log forwarder:

```cs
var loggerConfig = new LoggerConfiguration();

loggerConfig
    .Enrich.WithThreadName()
    .Enrich.WithThreadId()    
    .Enrich.WithNewRelicLogsInContext()
    .WriteTo.File( path: @"C:\logs\ExistingLoggingOutput.txt")
    .WriteTo.File(
        formatter: new NewRelicFormatter(), 
        path: @"C:\logs\SerilogExample.log.json");

var log = loggerConfig.CreateLogger();
```

This configuration results in new JSON files that are written to disk. Some of these [configuration options](https://github.com/serilog/serilog-sinks-file) may be useful for managing the amount of disk space used and/or the performance of the sink.

* `restrictedToMinimumLevel`
* `buffered`
* `rollingInterval`
* `rollOnFileSizeLimit`
* `retainedFileCountLimit`

Although not required, using the [Serilog Asynchronous Sink Wrapper](https://www.nuget.org/packages/Serilog.Sinks.Async) may help improve the performance by performing formatting and output of log files on a different thread.

3. Once you have configured the Serilog extension and updated your logging file, there are [several options](/docs/logs/forward-logs/enable-log-management-new-relic/#log-forwarding) for forwarding your logs. Here is an example configuration using the infrastructure agent for logs in context:

  ```yml
  logs:
    - name: application-log
      file: C:\logs\log4netExample.log.json # Path to a single log file
  ```

  [Documentation for using the infrastructure agent forwarder](/docs/logs/forward-logs/forward-your-logs-using-infrastructure-agent/#file)

<Collapser id="serilog-file" title="Serilog file-based configuration"

You can also configure the New Relic Serilog extension with file-based configuration providers.The following additional NuGet Packages are required:

* [Microsoft.Extensions.Configuration](https://www.nuget.org/packages/Microsoft.Extensions.Configuration/)
* [Serilog.Settings.Configuration](https://www.nuget.org/packages/Serilog.Settings.Configuration)

The following example code creates a logger based on settings contained in an `appSettings.json` file.

<DoNotTranslate>**Instantiating logger using `appsettings.json`**</DoNotTranslate>

```cs
var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json");

var configuration = builder.Build();

var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    .CreateLogger();
```

<DoNotTranslate>**Sample `appsettings.json` file**</DoNotTranslate>

```json
{
    "Serilog": {
        "Using": [
            "Serilog.Sinks.Console",
            "Serilog.Sinks.File",
            "NewRelic.LogEnrichers.Serilog"
        ],
        "MinimumLevel": "Debug",
        "Enrich": [
            "WithNewRelicLogsInContext"
        ],
        "WriteTo": [
            {
                "Name": "File",
                "Args": {
                    "path": "C:\\Logs\\SerilogExample.log.json",
                    "formatter": "NewRelic.LogEnrichers.Serilog.NewRelicFormatter, NewRelic.LogEnrichers.Serilog"
                }
            }
        ],
        "Properties": {
            "Application": "NewRelic Logging Serilog Example"
        }
    }
}
```

The following example code creates a logger based on settings contained in a `web.config` file. The [Serilog.Settings.AppSettings](https://www.nuget.org/packages/Serilog.Settings.AppSettings) NuGet Package is required.

<DoNotTranslate>**Instantiating logger using `.config` file**</DoNotTranslate>

```cs
var logger = new LoggerConfiguration()
    .ReadFrom.AppSettings()
    .CreateLogger();
```

<DoNotTranslate>**Sample `web.config` file**</DoNotTranslate>

```xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="serilog:using:NewRelic" value="NewRelic.LogEnrichers.Serilog" />
    <add key="serilog:using:File" value="Serilog.Sinks.File" />
    <!--Add other enrichers here-->
    <add key="serilog:enrich:WithNewRelicLogsInContext" />
    <add key="serilog:write-to:File.path" value="C:\logs\SerilogExample.log.json" />
    <add key="serilog:write-to:File.formatter" value="NewRelic.LogEnrichers.Serilog.NewRelicFormatter, NewRelic.LogEnrichers.Serilog" />
  </appSettings>
```