forked from kbabiy/LogCast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoggingMiddleware.cs
65 lines (54 loc) · 2.16 KB
/
LoggingMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using LogCast.Loggers.Elapsed;
using JetBrains.Annotations;
using Microsoft.Owin;
namespace LogCast.Owin
{
using AppFunc = Func<IDictionary<string, object>, Task>;
[UsedImplicitly(ImplicitUseTargetFlags.WithMembers)]
public class LoggingMiddleware
{
public ILogger Logger { get; }
public Func<IOwinContext, ILogger, IOwinContextLogMap> OwinContextLogMapFactory { get; }
public LoggingMiddleware()
: this(LogManager.GetLogger(), (owinContext, logger) => new OwinContextLogMap(owinContext))
{
}
public LoggingMiddleware(
ILogger logger,
Func<IOwinContext, ILogger, IOwinContextLogMap> owinContextLogMapFactory)
{
Logger = logger ?? throw new ArgumentNullException(nameof(logger));
OwinContextLogMapFactory = owinContextLogMapFactory ?? throw new ArgumentNullException(nameof(owinContextLogMapFactory));
}
public Func<AppFunc, AppFunc> GetApplicationFunction()
{
return next => environment => Invoke(next, environment);
}
public async Task Invoke(AppFunc next, IDictionary<string, object> environment)
{
if (next == null) throw new ArgumentNullException(nameof(next));
if (environment == null) throw new ArgumentNullException(nameof(environment));
using (var logContext = new LogCastContext())
{
var context = new OwinContext(environment);
var owinContextLogMap = OwinContextLogMapFactory(context, Logger);
using (new ElapsedLogger(Logger, context.Request.Method))
{
try
{
await next(environment);
}
catch (Exception exception)
{
Logger.Error(exception);
context.Response.StatusCode = 500;
}
owinContextLogMap.AfterNextHandler(logContext);
}
}
}
}
}