forked from scriptcs/scriptcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogProviderExtensions.cs
More file actions
67 lines (56 loc) · 1.96 KB
/
LogProviderExtensions.cs
File metadata and controls
67 lines (56 loc) · 1.96 KB
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
66
67
namespace ScriptCs.Contracts
{
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
public static class LogProviderExtensions
{
public static ILog For<T>(this ILogProvider provider)
{
return provider.For(typeof(T));
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ILog ForCurrentType(this ILogProvider provider)
{
return provider.For(new StackFrame(1, false).GetMethod().DeclaringType);
}
public static ILog For(this ILogProvider provider, Type type)
{
return provider.For(type.FullName);
}
public static ILog For(this ILogProvider provider, string name)
{
return new LoggerExecutionWrapper(provider.GetLogger(name));
}
private class LoggerExecutionWrapper : ILog
{
private const string FailedToGenerateLogMessage = "Failed to generate log message";
private readonly Logger _logger;
internal LoggerExecutionWrapper(Logger logger)
{
_logger = logger;
}
public bool Log(
LogLevel logLevel, Func<string> createMessage, Exception exception = null, params object[] formatArgs)
{
if (createMessage == null)
{
return _logger(logLevel, null);
}
Func<string> wrappedMessageFunc = () =>
{
try
{
return createMessage();
}
catch (Exception ex)
{
Log(LogLevel.Error, () => FailedToGenerateLogMessage, ex);
}
return null;
};
return _logger(logLevel, wrappedMessageFunc, exception, formatArgs);
}
}
}
}