Skip to content

Commit fda0c1b

Browse files
author
Сергей Трегуб
committed
Log unhandled exceptions
Issue #8
1 parent 99dc1c6 commit fda0c1b

1 file changed

Lines changed: 20 additions & 9 deletions

File tree

ProjectTemplates/ReferenceProject/Program.cs

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,30 @@
66
using Serilog;
77
using Microsoft.Extensions.Hosting;
88
using System.IO;
9+
using System;
910

1011
namespace ReferenceProject
1112
{
1213
public class Program
1314
{
14-
public static void Main(string[] args)
15+
public static int Main(string[] args)
1516
{
16-
CreateHostBuilder(args).Build().Run();
17+
try
18+
{
19+
CreateHostBuilder(args).Build().Run();
20+
21+
return 0;
22+
}
23+
catch(Exception ex)
24+
{
25+
var msg = "An unhandled exception occurred. The application will be closed";
26+
Log.Logger?.Fatal(ex, msg);
27+
if( Log.Logger == null )
28+
{
29+
Console.WriteLine(msg + Environment.NewLine + ex);
30+
}
31+
return 1;
32+
}
1733
}
1834

1935
public static IHostBuilder CreateHostBuilder(string[] args) =>
@@ -31,17 +47,12 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
3147
{
3248
logging.ClearProviders();
3349

34-
/*
35-
* You can use a global logger as this, but I don't recommend this way
36-
* More information: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#logging
50+
// https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#logging
3751
Log.Logger = new LoggerConfiguration()
3852
.ReadFrom.Configuration(context.Configuration)
3953
.CreateLogger();
40-
*/
4154

42-
logging.AddSerilog(new LoggerConfiguration()
43-
.ReadFrom.Configuration(context.Configuration)
44-
.CreateLogger());
55+
logging.AddSerilog(Log.Logger);
4556
})
4657
.ConfigureWebHostDefaults(webBuilder =>
4758
{

0 commit comments

Comments
 (0)