Skip to content

Commit

Permalink
Merge pull request #66 from nblumhardt/serilog-4
Browse files Browse the repository at this point in the history
Update to Serilog 4
  • Loading branch information
nblumhardt authored Jun 9, 2024
2 parents 63537e2 + 35d4901 commit 69e2dab
Show file tree
Hide file tree
Showing 8 changed files with 210 additions and 213 deletions.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ A simple `Hello, {User}` event.
Install from [NuGet](https://nuget.org/packages/Serilog.Formatting.Compact):

```powershell
Install-Package Serilog.Formatting.Compact
dotnet add package Serilog.Formatting.Compact
```

The formatter is used in conjunction with sinks that accept `ITextFormatter`. For example, the [file](https://github.com/serilog/serilog-sinks-file) sink:
Expand All @@ -26,6 +26,7 @@ Log.Logger = new LoggerConfiguration()
.CreateLogger();
```
#### XML `<appSettings>` configuration

To specify the formatter in XML `<appSettings>` provide its assembly-qualified type name:

```xml
Expand Down Expand Up @@ -154,3 +155,7 @@ Several tools are available for working with the CLEF format.
* **[Compact Log Format Viewer](https://github.com/warrenbuckley/Compact-Log-Format-Viewer)** - a cross-platform viewer for CLEF files
* **[`seqcli`](https://github.com/datalust/seqcli)** - pretty-`print` CLEF files at the command-line, or `ingest` CLEF files into [Seq](https://datalust.co/seq) for search, and analysis
* **[_Serilog.Formatting.Compact.Reader_](https://github.com/serilog/serilog-formatting-compact-reader)** - convert CLEF documents back into Serilog `LogEvent`s

### Customizing output

_Serilog.Formatting.Compact_ is not intended to provide customizable formatters. See [this blog post](https://nblumhardt.com/2021/06/customize-serilog-json-output/) for comprehensive Serilog JSON output customization examples.
4 changes: 1 addition & 3 deletions appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ version: '{build}'
skip_tags: true
image: Visual Studio 2022
configuration: Release
install:
- ps: ./Setup.ps1
build_script:
- ps: ./Build.ps1
- pwsh: ./Build.ps1
test: false
artifacts:
- path: artifacts/Serilog.*.nupkg
Expand Down
5 changes: 0 additions & 5 deletions global.json

This file was deleted.

184 changes: 92 additions & 92 deletions src/Serilog.Formatting.Compact/CompactJsonFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,117 +21,117 @@
using Serilog.Parsing;
// ReSharper disable MemberCanBePrivate.Global

namespace Serilog.Formatting.Compact
namespace Serilog.Formatting.Compact;

/// <summary>
/// An <see cref="ITextFormatter"/> that writes events in a compact JSON format.
/// </summary>
public class CompactJsonFormatter: ITextFormatter
{
readonly JsonValueFormatter _valueFormatter;

/// <summary>
/// An <see cref="ITextFormatter"/> that writes events in a compact JSON format.
/// Construct a <see cref="CompactJsonFormatter"/>, optionally supplying a formatter for
/// <see cref="LogEventPropertyValue"/>s on the event.
/// </summary>
public class CompactJsonFormatter: ITextFormatter
/// <param name="valueFormatter">A value formatter, or null.</param>
public CompactJsonFormatter(JsonValueFormatter? valueFormatter = null)
{
readonly JsonValueFormatter _valueFormatter;

/// <summary>
/// Construct a <see cref="CompactJsonFormatter"/>, optionally supplying a formatter for
/// <see cref="LogEventPropertyValue"/>s on the event.
/// </summary>
/// <param name="valueFormatter">A value formatter, or null.</param>
public CompactJsonFormatter(JsonValueFormatter valueFormatter = null)
{
_valueFormatter = valueFormatter ?? new JsonValueFormatter(typeTagName: "$type");
}
_valueFormatter = valueFormatter ?? new JsonValueFormatter(typeTagName: "$type");
}

/// <summary>
/// Format the log event into the output. Subsequent events will be newline-delimited.
/// </summary>
/// <param name="logEvent">The event to format.</param>
/// <param name="output">The output.</param>
public void Format(LogEvent logEvent, TextWriter output)
{
FormatEvent(logEvent, output, _valueFormatter);
output.WriteLine();
}
/// <summary>
/// Format the log event into the output. Subsequent events will be newline-delimited.
/// </summary>
/// <param name="logEvent">The event to format.</param>
/// <param name="output">The output.</param>
public void Format(LogEvent logEvent, TextWriter output)
{
FormatEvent(logEvent, output, _valueFormatter);
output.WriteLine();
}

/// <summary>
/// Format the log event into the output.
/// </summary>
/// <param name="logEvent">The event to format.</param>
/// <param name="output">The output.</param>
/// <param name="valueFormatter">A value formatter for <see cref="LogEventPropertyValue"/>s on the event.</param>
public static void FormatEvent(LogEvent logEvent, TextWriter output, JsonValueFormatter valueFormatter)
{
if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
if (output == null) throw new ArgumentNullException(nameof(output));
if (valueFormatter == null) throw new ArgumentNullException(nameof(valueFormatter));
/// <summary>
/// Format the log event into the output.
/// </summary>
/// <param name="logEvent">The event to format.</param>
/// <param name="output">The output.</param>
/// <param name="valueFormatter">A value formatter for <see cref="LogEventPropertyValue"/>s on the event.</param>
public static void FormatEvent(LogEvent logEvent, TextWriter output, JsonValueFormatter valueFormatter)
{
if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
if (output == null) throw new ArgumentNullException(nameof(output));
if (valueFormatter == null) throw new ArgumentNullException(nameof(valueFormatter));

output.Write("{\"@t\":\"");
output.Write(logEvent.Timestamp.UtcDateTime.ToString("O"));
output.Write("\",\"@mt\":");
JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Text, output);
output.Write("{\"@t\":\"");
output.Write(logEvent.Timestamp.UtcDateTime.ToString("O"));
output.Write("\",\"@mt\":");
JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Text, output);

var tokensWithFormat = logEvent.MessageTemplate.Tokens
.OfType<PropertyToken>()
.Where(pt => pt.Format != null);
var tokensWithFormat = logEvent.MessageTemplate.Tokens
.OfType<PropertyToken>()
.Where(pt => pt.Format != null);

// Better not to allocate an array in the 99.9% of cases where this is false
// Better not to allocate an array in the 99.9% of cases where this is false
// ReSharper disable once PossibleMultipleEnumeration
if (tokensWithFormat.Any())
{
output.Write(",\"@r\":[");
var delim = "";
// ReSharper disable once PossibleMultipleEnumeration
if (tokensWithFormat.Any())
foreach (var r in tokensWithFormat)
{
output.Write(",\"@r\":[");
var delim = "";
foreach (PropertyToken r in tokensWithFormat)
{
output.Write(delim);
delim = ",";
var space = new StringWriter();
r.Render(logEvent.Properties, space, CultureInfo.InvariantCulture);
JsonValueFormatter.WriteQuotedJsonString(space.ToString(), output);
}
output.Write(']');
output.Write(delim);
delim = ",";
var space = new StringWriter();
r.Render(logEvent.Properties, space, CultureInfo.InvariantCulture);
JsonValueFormatter.WriteQuotedJsonString(space.ToString(), output);
}
output.Write(']');
}

if (logEvent.Level != LogEventLevel.Information)
{
output.Write(",\"@l\":\"");
output.Write(logEvent.Level);
output.Write('\"');
}
if (logEvent.Level != LogEventLevel.Information)
{
output.Write(",\"@l\":\"");
output.Write(logEvent.Level);
output.Write('\"');
}

if (logEvent.Exception != null)
{
output.Write(",\"@x\":");
JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
}
if (logEvent.Exception != null)
{
output.Write(",\"@x\":");
JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
}

if (logEvent.TraceId != null)
{
output.Write(",\"@tr\":\"");
output.Write(logEvent.TraceId.Value.ToHexString());
output.Write('\"');
}
if (logEvent.TraceId != null)
{
output.Write(",\"@tr\":\"");
output.Write(logEvent.TraceId.Value.ToHexString());
output.Write('\"');
}

if (logEvent.SpanId != null)
{
output.Write(",\"@sp\":\"");
output.Write(logEvent.SpanId.Value.ToHexString());
output.Write('\"');
}
if (logEvent.SpanId != null)
{
output.Write(",\"@sp\":\"");
output.Write(logEvent.SpanId.Value.ToHexString());
output.Write('\"');
}

foreach (var property in logEvent.Properties)
foreach (var property in logEvent.Properties)
{
var name = property.Key;
if (name.Length > 0 && name[0] == '@')
{
var name = property.Key;
if (name.Length > 0 && name[0] == '@')
{
// Escape first '@' by doubling
name = '@' + name;
}

output.Write(',');
JsonValueFormatter.WriteQuotedJsonString(name, output);
output.Write(':');
valueFormatter.Format(property.Value, output);
// Escape first '@' by doubling
name = '@' + name;
}

output.Write('}');
output.Write(',');
JsonValueFormatter.WriteQuotedJsonString(name, output);
output.Write(':');
valueFormatter.Format(property.Value, output);
}

output.Write('}');
}
}
}
53 changes: 26 additions & 27 deletions src/Serilog.Formatting.Compact/EventIdHash.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,39 +14,38 @@

using System;

namespace Serilog.Formatting.Compact
namespace Serilog.Formatting.Compact;

/// <summary>
/// Hash functions for message templates. See <see cref="Compute"/>.
/// </summary>
public static class EventIdHash
{
/// <summary>
/// Hash functions for message templates. See <see cref="Compute"/>.
/// Compute a 32-bit hash of the provided <paramref name="messageTemplate"/>.
/// The resulting hash value can be uses as an event id in lieu of transmitting
/// the full template string.
/// </summary>
public static class EventIdHash
/// <param name="messageTemplate">A message template.</param>
/// <returns>A 32-bit hash of the template.</returns>
public static uint Compute(string messageTemplate)
{
/// <summary>
/// Compute a 32-bit hash of the provided <paramref name="messageTemplate"/>.
/// The resulting hash value can be uses as an event id in lieu of transmitting
/// the full template string.
/// </summary>
/// <param name="messageTemplate">A message template.</param>
/// <returns>A 32-bit hash of the template.</returns>
public static uint Compute(string messageTemplate)
{
if (messageTemplate == null) throw new ArgumentNullException(nameof(messageTemplate));
if (messageTemplate == null) throw new ArgumentNullException(nameof(messageTemplate));

// Jenkins one-at-a-time https://en.wikipedia.org/wiki/Jenkins_hash_function
unchecked
// Jenkins one-at-a-time https://en.wikipedia.org/wiki/Jenkins_hash_function
unchecked
{
uint hash = 0;
for (var i = 0; i < messageTemplate.Length; ++i)
{
uint hash = 0;
for (var i = 0; i < messageTemplate.Length; ++i)
{
hash += messageTemplate[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
hash += messageTemplate[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
}
}
}
Loading

0 comments on commit 69e2dab

Please sign in to comment.