Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created December 4, 2018 04:01
Show Gist options
  • Save ichiroku11/990d9fa349c798094b91cd90b185a4b6 to your computer and use it in GitHub Desktop.
Save ichiroku11/990d9fa349c798094b91cd90b185a4b6 to your computer and use it in GitHub Desktop.
ASP.NET Core MVCでSerilogを使う
{
"Serilog": {
"Using": [
"Serilog.Sinks.File",
"Serilog.Formatting.Compact"
],
"WriteTo": [
{
"Name": "File",
"Args": {
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
"path": ".\\log\\webapp.txt",
"restrictedToMinimumLevel": "Information",
"rollingInterval": "Day"
}
}
]
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace WebApp.Controllers {
public class HomeController : Controller {
private readonly ILogger _logger;
public HomeController(ILogger<HomeController> logger) {
_logger = logger;
}
public IActionResult Index() {
// ログを出力
_logger.LogInformation(
"Log {@param}",
new { controller = "Home", action = "Index" });
return Content("Home.Index");
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Compact;
namespace WebApp {
public class Program {
public static void Main(string[] args) {
// appsettings.jsonを読み込む準備
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
// ロガーを構築する
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger();
/*
// ロガーを構築する
Log.Logger = new LoggerConfiguration()
// ファイルに書き込む
.WriteTo.File(
// JSON形式で出力
formatter: new CompactJsonFormatter(),
path: @".\log\webapp.txt",
restrictedToMinimumLevel: LogEventLevel.Information,
// 日付ごとに新しいファイルを作る
rollingInterval: RollingInterval.Day)
.CreateLogger();
*/
try {
Log.Information("Starting Web Host");
CreateWebHostBuilder(args)
.Build()
.Run();
} catch (Exception exception) {
Log.Fatal(exception, "Host terminated unexpectedly");
} finally {
Log.CloseAndFlush();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
// ログプロバイダーとしてSerilogを使う
.UseSerilog();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment