Dmitry Mubarakshin
Dmitry Mubarakshin

Reputation: 75

Using Serilog in ASP.NET MVC project

Today at work I was asked to add some basic logging functionality in my existing ASP.NET MVC (not Core) project. I was told to use Serilog for this.

However, I failed to find any reasonable example of using Serilog in MVC, all links simply refer to Core. I tried to do everything myself. After installing all necessary packages (Serilog, Serilog.Sinks.File), I created a "Logs" folder and tried this:

var log = new LoggerConfiguration()
  .WriteTo.File("~/Logs/log.txt")
  .CreateLogger();

log.Information("Hello from Serilog!");

I expected to see a new file in the folder but there wasn't any. I also tried using a simpler path "log.txt" and creating a file in this folder preemptively but it didn't help.

Is it possible that Serilog is not supported for MVC at all? If it is, what is a simple way to log something into a text file?

Upvotes: 6

Views: 9575

Answers (1)

mason
mason

Reputation: 32702

I doubt Serilog understands the ~/ syntax in your path to your log file. ~/ refers to the virtual root of your site, but Serilog doesn't know anything about virtual roots or websites. It's just a logging framework and expects a normal path. So if you want to log to a file called log.txt in the Logs directory of your site, then you need to convert it to a proper path that Serilog can understand.

The System.Web.Hosting.HostingEnvironment.MapPath method can translate virtual root relative paths. So ~/Logs/log.txt can become something like C:\path-to-your-site\Logs\log.txt.

Change to this:

var log = new LoggerConfiguration()
    .WriteTo.File(System.Web.Hosting.HostingEnvironment.MapPath("~/Logs/log.txt"))
    .CreateLogger();

log.Information("Hello from Serilog!");    

//note that importing the namespace will make it so you don't have to fully qualify the name.

Then Serilog should log to the location you're expecting, if the directory exists and it has write privileges there.

File logging from a web application is going to get very messy. Unless your site gets hardly any usage, the logs are going to become unmanageable and useless. I suggest you look at the other Serilog sinks, and find one that logs to a logging service such as Seq (from the makers of Serilog) or Stackify Retrace.

Upvotes: 9

Related Questions