-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathLogCommand.cs
163 lines (136 loc) · 5.66 KB
/
LogCommand.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
using System;
// Copyright 2018 Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SeqCli.Api;
using SeqCli.Cli.Features;
using SeqCli.Connection;
using SeqCli.Output;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Compact.Reader;
// ReSharper disable UnusedType.Global, UseAwaitUsing, MethodHasAsyncOverload
namespace SeqCli.Cli.Commands;
[Command("log", "Send a structured log event to the server", Example = "seqcli log -m 'Hello, {Name}!' -p Name=World -p App=Test")]
class LogCommand : Command
{
readonly SeqConnectionFactory _connectionFactory;
readonly PropertiesFeature _properties;
readonly ConnectionFeature _connection;
string? _message, _level, _timestamp, _exception;
readonly PropertiesExpressionFeature _propertiesExpression;
public LogCommand(SeqConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory));
Options.Add(
"m=|message=",
"A message to associate with the event (the default is to send no message); https://messagetemplates.org syntax is supported",
v => _message = v);
Options.Add(
"l=|level=",
"The level or severity of the event (the default is `Information`)",
v => _level = v);
Options.Add(
"t=|timestamp=",
"The event timestamp as ISO-8601 (the current UTC timestamp will be used by default)",
v => _timestamp = v);
Options.Add(
"x=|exception=",
"Additional exception or error information to send, if any",
v => _exception = v);
_properties = Enable<PropertiesFeature>();
_propertiesExpression = Enable<PropertiesExpressionFeature>();
_connection = Enable<ConnectionFeature>();
}
protected override async Task<int> Run()
{
var payload = new JObject
{
["@t"] = string.IsNullOrWhiteSpace(_timestamp) ? DateTimeOffset.Now.ToString("o") : _timestamp
};
if (_level != null && _level != "Information")
payload["@l"] = _level;
if (!string.IsNullOrWhiteSpace(_message))
payload["@mt"] = _message;
if (!string.IsNullOrWhiteSpace(_exception))
payload["@x"] = _exception;
StringContent content;
if (_propertiesExpression.GetEnricher() is { } enricher)
{
var jo = JObject.FromObject(payload);
var evt = LogEventReader.ReadFromJObject(jo);
// We're breaking the nullability contract of `ILogEventEnricher.Enrich()`, here.
enricher.Enrich(evt, null!);
foreach (var (key, value) in _properties.Properties)
{
if (string.IsNullOrWhiteSpace(key))
continue;
var name = key.Trim();
evt.AddOrUpdateProperty(new LogEventProperty(name, new ScalarValue(value)));
}
var sw = new StringWriter();
OutputFormatter.Json.Format(evt, sw);
content = new StringContent(sw.ToString(), Encoding.UTF8, ApiConstants.ClefMediaType);
}
else
{
// Explicit properties override computed ones.
foreach (var (key, value) in _properties.Properties)
{
if (string.IsNullOrWhiteSpace(key))
continue;
var name = key.Trim();
if (name.StartsWith('@'))
name = $"@{name}";
payload[name] = new JValue(value);
}
using var sw = new StringWriter();
using var jsonWriter = new JsonTextWriter(sw);
payload.WriteTo(jsonWriter);
jsonWriter.Flush();
sw.WriteLine();
content = new StringContent(sw.ToString(), Encoding.UTF8, ApiConstants.ClefMediaType);
}
var connection = _connectionFactory.Connect(_connection);
var (_, apiKey) = _connectionFactory.GetConnectionDetails(_connection);
var request = new HttpRequestMessage(HttpMethod.Post, ApiConstants.IngestionEndpoint) {Content = content};
if (apiKey != null)
request.Headers.Add(ApiConstants.ApiKeyHeaderName, apiKey);
var result = await connection.Client.HttpClient.SendAsync(request);
if (result.IsSuccessStatusCode)
return 0;
var resultJson = await result.Content.ReadAsStringAsync();
if (!string.IsNullOrWhiteSpace(resultJson))
{
try
{
var error = JsonConvert.DeserializeObject<dynamic>(resultJson)!;
Log.Error("Failed with status code {StatusCode}: {ErrorMessage}",
result.StatusCode,
(string) error.ErrorMessage);
}
catch
{
// ignored
}
}
Log.Error("Failed with status code {StatusCode} ({ReasonPhrase})", result.StatusCode, result.ReasonPhrase);
return 1;
}
}