forked from datalust/seqcli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogCommand.cs
More file actions
154 lines (127 loc) · 4.89 KB
/
LogCommand.cs
File metadata and controls
154 lines (127 loc) · 4.89 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
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
using System;
using System.Collections.Generic;
// 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.Config;
using Serilog;
// ReSharper disable 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 PropertiesFeature _properties;
readonly ConnectionFeature _connection;
readonly StoragePathFeature _storagePath;
string? _message, _level, _timestamp, _exception;
public LogCommand()
{
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>();
_connection = Enable<ConnectionFeature>();
_storagePath = Enable<StoragePathFeature>();
}
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;
foreach (var (key, value) in _properties.NestedProperties)
{
if (string.IsNullOrWhiteSpace(key))
continue;
var name = key.Trim();
if (name.StartsWith('@'))
name = $"@{name}";
payload[name] = ToJsonValue(value);
}
StringContent content;
using (var builder = new StringWriter())
using (var jsonWriter = new JsonTextWriter(builder))
{
payload.WriteTo(jsonWriter);
jsonWriter.Flush();
builder.WriteLine();
content = new StringContent(builder.ToString(), Encoding.UTF8, ApiConstants.ClefMediaType);
}
var config = RuntimeConfigurationLoader.Load(_storagePath);
var connection = SeqConnectionFactory.Connect(_connection, config);
var (_, apiKey) = SeqConnectionFactory.GetConnectionDetails(_connection, config);
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;
}
static JToken ToJsonValue(object? value)
{
if (value is not IReadOnlyDictionary<string, object?> rod)
{
return new JValue(value);
}
var result = new JObject();
foreach (var (key, sub) in rod)
{
result[key] = ToJsonValue(sub);
}
return result;
}
}