1

I have a web application using ASP.NET 5. I'm just getting familiarized with the new built-in logging mechanisms (Microsoft.Extensions.Logging).

I was using NLog in other applications prior to this, and NLog has an mechanism to automatically delete log files after a certain period. Is there any way at all to replicate this behavior in ASP.NET built in logging? For example, delete log files that are > 7 days old?

I wasn't able to find documentation on this elsewhere...

Steven
  • 166,672
  • 24
  • 332
  • 435
painiyff
  • 2,519
  • 6
  • 21
  • 29

1 Answers1

2

We can still use NLog. The ASP.NET Logging repository says:

Community projects adapt Microsoft.Extensions.Logging for use with different back-ends.

That includes NLog. Here is the NLog - provider for the NLog library, and what follows is a simplified demo. You can tweak it for your purposes.

Directory Structure

MyProject
  nlog.config
  project.json
  Startup.cs

Startup.cs

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
using NLog.Extensions.Logging;

public class Startup
{
    public void Configure(
        IApplicationBuilder app, 
        IHostingEnvironment env, 
        ILoggerFactory loggerFactory)
    {
        //add NLog to aspnet5
        loggerFactory.AddNLog();

        //add NLog.Web (only needed if NLog.Web.ASPNET5 is needed)
        app.AddNLogWeb();

        //configure nlog.config in your project root
        env.ConfigureNLog("./MyProject/nlog.config");

        // we can also do this from a controller
        // if we inject ILoggerFactory
        var logger = loggerFactory.CreateLogger("NLog Demo"); 
        logger.LogInformation("Hello from NLog");
    }    
}

project.json

{
    "dependencies": {
        "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
        "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
        "NLog.Extensions.Logging": "1.0.0-rc1-final-2016-02-06",
        "NLog.Web.ASPNET5": "4.2.1"
    },
    "frameworks": {
        "dnx451": {}
    },
    "commands": {
        "web": "Microsoft.AspNet.Server.Kestrel"
    }
}

nlog.config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Warn"
      archiveEvery="Minute"
      archiveNumbering="Rolling"
      maxArchiveFiles="1">

  <extensions>
    <add assembly="NLog.Web.ASPNET5"/>
  </extensions>

  <targets>
    <target xsi:type="File" name="demo-file" 
         fileName="c:\temp\demo-file-${shortdate}.txt" 
         layout="${message}" />
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="demo-file" />
  </rules>
</nlog>
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467