This repository has been archived by the owner on Jun 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
MinimalLogDataBuilder.cs
73 lines (63 loc) · 2.04 KB
/
MinimalLogDataBuilder.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
66
67
68
69
70
71
72
73
using System;
using System.Diagnostics;
using log4net;
using log4net.Core;
using log4net.Util;
using Newtonsoft.Json;
namespace uShip.Logging.LogBuilders
{
public interface IMinimalLogDataBuilder
{
IMinimalLogDataBuilder Message(string message);
IMinimalLogDataBuilder WithRawJsonObject(string jsonData);
IMinimalLogDataBuilder WithSeverity(Severity? severity);
void Write();
}
public class MinimalLogDataBuilder : IMinimalLogDataBuilder
{
private readonly ILog _log;
private readonly LoggingEventDataBuilder _loggingEventDataBuilder;
private string _message;
private string _jsonData = null;
private Severity? _severity;
public MinimalLogDataBuilder(ILog log, LoggingEventDataBuilder loggingEventDataBuilder)
{
_log = log;
_loggingEventDataBuilder = loggingEventDataBuilder;
}
public IMinimalLogDataBuilder Message(string message)
{
_message = message;
return this;
}
public IMinimalLogDataBuilder WithRawJsonObject(string jsonData)
{
if (!string.IsNullOrEmpty(jsonData))
_jsonData = jsonData;
return this;
}
public IMinimalLogDataBuilder WithSeverity(Severity? severity)
{
_severity = severity;
return this;
}
public void Write()
{
var properties = new PropertiesDictionary();
if (_jsonData != null)
{
try
{
properties["data"] = JsonConvert.DeserializeObject(_jsonData);
}
catch (Exception)
{
properties["data"] = _jsonData;
}
}
var frame = new StackTrace().GetFrame(0);
var logEvent = _loggingEventDataBuilder.Build(frame, _severity ?? Severity.Info, _message, null, properties);
_log.Logger.Log(new LoggingEvent(logEvent));
}
}
}