Setting up Serilog for my .net core app, everything compiles and runs but not writing to the file. How can I pinpoint the problem?
I am only use Serilog package - but there seems to be a multitude of others, and I'd be happy to use another one.
In my startup.cs I have
using Serilog;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.ReadFrom.Configuration(configuration)
.CreateLogger();
}
in my appsettings.json I have
{
"AllowedHosts": "*",
"Serilog": {
"MinimumLevel": "Debug",
"Override": {
"Microsoft.AspNetCore": "Warning"
},
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "C:\\log\\Batching\\apptest.log"
}
}
]
}
}
in my Program.cs I have
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
And finally I use this statement to test the writing:
Log.Information("write something to file");
It is not working. What can I try next?
Just as mentioned in the document:
To use the file sink with Microsoft.Extensions.Configuration, for example with ASP.NET Core or .NET Core, use the Serilog.Settings.Configuration package
And you could find introduction to different packages in this page:
https://github.com/serilog
I tried with the packages:
Set as below in program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.UseSerilog((context, configuration) =>
{
var config = context.Configuration;
configuration.ReadFrom.Configuration(config);
});
It works well in my case:
Update:
I configured as below in appsettings.json:
I also tried with the absolute path of my desktop, it worked either
Related
I'm trying to use serligo as my main logging utilitie but I can't seem to get it to work correctly.
In the Program.cs file, I configure the logger and also log a startup message, this message gets outputted to the console.
I also have, in one of my controllers, an ILogger<HomeController> instance that logs information when a certain action is called. These logs are not outputted to the console, and I cannot understand why.
Startup.cs
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
try
{
Log.Information("Starting up version {version}", Defaults.Version); // WORKS
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application start-up failed");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration))
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Controller
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("Home/Index"); //Does not work
return View();
}
}
appsettings.json
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Verbose",
"Override": {
"Microsoft": "Warning",
"Microsoft.AspNetCore": "Warning",
"System": "Error"
}
},
"WriteTo": [
{
"Name": "Async",
"Args": {
"configure": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
"formatter": "Serilog.Formatting.Compact.RenderedCompactJsonFormatter, Serilog.Formatting.Compact"
}
}
]
}
}
]
},
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration))
The issue relates the above code, in this part of code, you should also configure it to write to the console.
Modify the code as below:
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration).WriteTo.Console())
Then, the output like this:
i have simple method
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(builder => builder.UseStartup<Startup>());
}
and i am write appsettings:
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http1AndHttp2"
},
"Endpoints": {
"Api": {
"Url": "https://+:5005",
"Protocols": "Http1AndHttp2"
},
"Grpc": {
"Url": "http://+:5006",
"Protocols": "Http2"
}
}
}
but when i start app, i see warning:
"Microsoft.AspNetCore.Server.Kestrel", "message": "Overriding address(es) 'https:\/\/localhost:5000, https:\/\/localhost:5001'. Binding to endpoints defined in UseKestrel() instead.", "addresses": "https:\/\/localhost:5000, https:\/\/localhost:5001
", "methodName": "UseKestrel()" }
and app start at standard port 5000, but i expect on port 5005
Why Kestrel changes the start port and how to make the application start on a given https://localhost:5005/api-docs/someService (i am use swagger)
As said on your application startup just do it in UseKestrel()
return Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(builder => builder.UseKestrel(x=>x.Listen(IPAddress.Any, 5005)).UseStartup<Startup>());
i am find that i need feel launchSettings.json with
"launchUrl": "https://localhost:5005/api-docs/SomeService"
My appsettings.json looks like this:
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "%APPDATA%\\FancyProject\\logs\\RR.log",
"formatter": "Serilog.Formatting.Json.JsonFormatter",
"rollingInterval": "Day",
"retainedFileCountLimit": 20,
"buffered": false
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId", "WithExceptionDetails" ],
"Properties": {
"Application": "SampleName"
}
}
}
Loading the settings:
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
I'd like to use the same config file for multiple projects in my solution but with a different application name in order to distinguish between services.
Is there a way to change the application name ("SampleName" in my config) in code when loading the config?
You can use the following extension method for IConfiguration interface to update the configuration instance after reading it from appsettings.json
public static class Ext
{
public static IConfiguration ApplyAppName(this IConfiguration configuration, string appName)
{
foreach (var (key, _) in configuration.AsEnumerable())
if (key.StartsWith("Serilog") && key.EndsWith("Application"))
configuration[key] = appName;
return configuration;
}
}
And use it in following way (based on
serilog-settings-configuration sample from GitHub) before configuring and creating a logger
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build()
.ApplyAppName("MyApp");
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Alternatively, you can follow Serilog integration for ASP.NET Core 2+ and use UseSerilog() method with the above ApplyAppName extension during CreateHostBuilder call
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); })
.UseSerilog((hostingContext, loggerConfiguration) =>
{
var config = hostingContext.Configuration.ApplyAppName("MyApp");
loggerConfiguration.ReadFrom.Configuration(config);
});
I solved it by removing the Properties section from the config and load it this way:
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.WithProperty("ApplicationName", "my application")
.CreateLogger();
PavelAnikhouski's (deleted) answer was actually the correct answer to my question but I think directly adding the correct application name is cleaner than modifying a placeholder.
I am using asp.net core(website) and Serilog for logging.
Nuget packages installed are
Serilog
Serilog.AspNetCore
Serilog.Extensions.Logging
Serilog.Extensions.Logging.File
Serilog.Settings.Configuration
Serilog.Sinks.File
Serilog.Sinks.RollingFile
Microsoft.Extensions.Logging
Settings in Main.cs file are :
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((WebHostBuilderContext, configurationBuilder) =>
{
configurationBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
configurationBuilder.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true);
configurationBuilder.AddEnvironmentVariables();
})
.ConfigureLogging((hostingContext, loggingBuilder) =>
{
loggingBuilder.ClearProviders();
loggingBuilder.AddSerilog();
})
.UseStartup<Startup>();
}
What is working :
In Startup.cs file if I write following code the logging file is getting created. Here I am specifying the configurations in code itself.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
string logFilePath = Path.Combine(env.ContentRootPath, "Logs/ImportManager2-{Date}.txt");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.RollingFile(logFilePath)
.CreateLogger();
loggerFactory.AddSerilog();
--
--
}
When I am using appsettings.json file with following content
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MyDatabaseLocal": "Server=_;Database=_;MultipleActiveResultSets=true;Connection Timeout=333;Integrated Security=SSPI",
"OtherDatabaseLocal": "Server=_;Database=_;MultipleActiveResultSets=true;Connection Timeout=333;Integrated Security=SSPI"
},
"Serilog": {
"MinimumLevel": "Debug",
"Override": {
"Microsoft": "Warning"
},
"Using": [
"Serilog.Sinks.Console",
"Serilog.Sinks.File"
],
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"path": "Logs/MyProject.txt"
}
}
]
}
}
and changed the startup.cs file like
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration.GetSection("Serilog"))
.CreateLogger();
loggerFactory.AddSerilog();
--
--
}
After this there is not file created. What could be the problem.
The following call is not quite working how you're expecting:
.ReadFrom.Configuration(Configuration.GetSection("Serilog"))
When using this extension method, Serilog expects that there will be a section named Serilog within the configuration that you pass through. In your example, you're passing the Serilog section itself, but then it's looking for another Serilog section within that.
Update the call to just pass through Configuration, like this:
.ReadFrom.Configuration(Configuration)
Serilog will find your Serilog section and consume the settings from that.
So I recently installed Application Insights to my project through Visual Studio and it says that it is 100% configured, but there is no added code in my Startup.cs. Do I need to add anything to get it fully functional or is that it?
There are 2 ways to add application insights to an ASP.NET Core site.
In the Program.cs file:
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights() // Here
.Build();
host.Run();
}
Or in the ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration); // here
var builder = services.AddMvc();
}
You need to add the instrumentation key in the appsettings.json file:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Information"
}
},
"ApplicationInsights": {
"InstrumentationKey": "4bbb7b98-78f8-49c3-8ede-da3215b75f43"
}
}