Logging to a file with .NET Core

In the .net Core 1.0 the simple logging to a file is not included by default. I wanted to use the default logger infrastructure and also add support for TextWriterTraceListener. This article is showing how to do this.

Configuration in appsettings.json

The standard appsettings.json configuration file has Logging section, even with LogLevel subsection and looks like this:

"Logging": {
   "IncludeScopes": false,
   "LogLevel": {
   "Default": "Warning"
Let's reuse what we have and provide Log location here:
"LogFile": ".\\logs\\log.txt",

in the Application folder would need to be created logs folder. If you use IIS hosting with, you would need to add permissions to this folder for dynamic pool identity user.

The main configuration

In the Configure method, which is in Startup.cs, add these lines:


The AddTextWriter is adding TextWriter output to logger factory configuration – from the Configuration (appsettings.json). Then, we are creating concrete logger for this one class and log Info level message.

The AddTextWriter uses same Extensions based configuration style, so I have created ILoggerFactoryExtensions class to host them. Here is the whole class:


The AddTraceSource is reading from Configuration file, and tries to find full path to produced file – based on value in appsettings.json. Then creates new “old” TextWriterTraceListener, which passes as loggerFactory as new TraceSource

The loggerFactory’s AddTraceSource is only available if you add Nuget package “Microsoft.Extensions.Logging.TraceSource”.

The .net core LogLevel, used as level for TraceSource can have a bit different values, then SourceLevels enum, so I have simple conversion there.

The actual use is already shown in Configure method above. Once configured, its using standard .net core LoggerFactory, which can be injected in required methods.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s