Skip to content

Commit

Permalink
in LogInfo
Browse files Browse the repository at this point in the history
  • Loading branch information
neuecc committed Feb 22, 2024
1 parent 0d247c0 commit cbed06c
Show file tree
Hide file tree
Showing 15 changed files with 74 additions and 62 deletions.
27 changes: 15 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,14 +228,14 @@ builder.Logging.AddZLoggerConsole(options =>
// e.g) "2023-12-01 16:41:55.775|Information|This is log message. (MyNamespace.MyApp)
options.UsePlainTextFormatter(formatter =>
{
formatter.SetPrefixFormatter($"{0}|{1}|", (template, info) => template.Format(info.Timestamp, info.LogLevel));
formatter.SetSuffixFormatter($" ({0})", (formatter, info) => formatter.Format(info.Category));
formatter.SetPrefixFormatter($"{0}|{1}|", (in MessageTemplate template, in LogInfo info) => template.Format(info.Timestamp, info.LogLevel));
formatter.SetSuffixFormatter($" ({0})", (in MessageTemplate template, in LogInfo info) => template.Format(info.Category));
formatter.SetExceptionFormatter((writer, ex) => Utf8String.Format(writer, $"{ex.Message}"));
});

// Using various variable formats.
// e.g) "2023-12-01T16:47:15+09:00|INF|This is log message"
formatter.SetPrefixFormatter($"{0:yyyy-MM-dd'T'HH:mm:sszzz}|{1:short}|", (writer, info) =>
formatter.SetPrefixFormatter($"{0:yyyy-MM-dd'T'HH:mm:sszzz}|{1:short}|", (in MessageTemplate template, in LogInfo info) =>
{
var escapeSequence = "";
// if (info.LogLevel >= LogLevel.Error)
Expand All @@ -247,7 +247,7 @@ builder.Logging.AddZLoggerConsole(options =>
// escapeSequence = "\u001b[38;5;08m";
// }
writer.Format(info.Timestamp, info.LogLevel);
template.Format(info.Timestamp, info.LogLevel);
});

// Console coloring example
Expand All @@ -256,7 +256,7 @@ builder.Logging.AddZLoggerConsole(options =>
// \u001b[31m => Red(ANSI Escape Code)
// \u001b[0m => Reset
// \u001b[38;5;***m => 256 Colors(08 is Gray)
formatter.SetPrefixFormatter($"{0}{1}|{2:short}|", (writer, info) =>
formatter.SetPrefixFormatter($"{0}{1}|{2:short}|", (in MessageTemplate template, in LogInfo info) =>
{
var escapeSequence = "";
if (info.LogLevel >= LogLevel.Error)
Expand All @@ -268,14 +268,14 @@ builder.Logging.AddZLoggerConsole(options =>
escapeSequence = "\u001b[38;5;08m";
}

writer.Format(escapeSequence, info.Timestamp, info.LogLevel);
template.Format(escapeSequence, info.Timestamp, info.LogLevel);
});

formatter.SetSuffixFormatter($"{0}", (writer, info) =>
formatter.SetSuffixFormatter($"{0}", (in MessageTemplate template, in LogInfo info) =>
{
if (info.LogLevel == LogLevel.Error || !info.Category.Name.Contains("MyApp"))
{
writer.Format("\u001b[0m");
template.Format("\u001b[0m");
}
});
});
Expand All @@ -288,24 +288,26 @@ Note: For format strings available for various variables:
-`LogLevel` can be specially specified as `short`. This reduces the length of string to a fixed number of characters, such as `INFO`.
- For other types, ZLogger uses [Cysharp/Utf8StringInterpolation](https://github.com/Cysharp/Utf8StringInterpolation) internally. Please see this.

`public delegate void MessageTemplateFormatter(in MessageTemplate template, in LogInfo info);`

| Name | Description |
|:-------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------|
| `SetPrefixFormatter(MessageTemplateHandler format, Action<MessageTemplate, LogInfo> formatter)` | Set the text to be given before the message body. (Default is empty) |
| `SetSuffixFormatter(MessageTemplateHandler format, Action<MessageTemplate, LogInfo> formatter)` | Set the text to be given after the message body. (Default is empty) |
| `SetPrefixFormatter(MessageTemplateHandler format, MessageTemplateFormatter formatter)` | Set the text to be given before the message body. (Default is empty) |
| `SetSuffixFormatter(MessageTemplateHandler format, MessageTemplateFormatter formatter)` | Set the text to be given after the message body. (Default is empty) |
| `SetExceptionFormatter(Action<IBufferWriter<byte>, Exception> formatter)` | |



### JSON

`public delegate void JsonLogInfoFormatter(Utf8JsonWriter jsonWriter, in LogInfo info);`

| Name | Description |
|:--------------------------------------------------------------------|:----------------------------------------------------------------------------------|
| `JsonPropertyNames JsonPropertyNames` | Specify the name of each key in the output JSON |
| `IncludeProperties IncludeProperties` | Flags that can specify properties to be output. (default: `Timestamp | LogLevel | CategoryName | Message | Exception | ScopeKeyValues | ParameterKeyValues`) |
| `JsonSerializerOptions JsonSerializerOptions` | The options of `System.Text.Json` |
| `Action<Utf8JsonWriter, LogInfo>? AdditionalFormatter` | Action when rendering additional properties based on `LogInfo`. |
| `JsonLogInfoFormatter? AdditionalFormatter` | Action when rendering additional properties based on `LogInfo`. |
| `JsonEncodedText? PropertyKeyValuesObjectName` | If set, the key/value properties is nested under the specified key name. |
| `IKeyNameMutator? KeyNameMutator` | You can set the naming convention if you want to automatically convert key names. |
| `bool UseUtcTimestamp` | If true, timestamp is output in utc. (default: false) |
Expand Down Expand Up @@ -357,7 +359,7 @@ public static class CloudLoggingExtensions
var eventId = Encode("eventId");
var userId = Encode("userId");

formatter.AdditionalFormatter = (writer, logInfo) =>
formatter.AdditionalFormatter = (Utf8JsonWriter writer, in LogInfo) =>
{
writer.WriteStartObject(labels);
writer.WriteString(category, logInfo.Category.JsonEncoded);
Expand Down Expand Up @@ -412,6 +414,7 @@ LogInfo
| `EventId EventId` | EventId of `Microsoft.Extensions.Logging` |
| `Exception? Exception` | Exception given as argument when logging. |
| `LogScopeState? ScopeState` | Additional properties set by `ILogger.BeginScope(...)` (if ZLoggerOptions.IncludeScopes = true) |
| `object? Context` | Additional context |
| `string? MemberName` | Caller MemberName |
| `string? FilePath` | Caller FilePath |
| `int LineNumber` | Caller LineNumber |
Expand Down
2 changes: 1 addition & 1 deletion sandbox/Benchmark/Benchmarks/PostLogEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public void SetUp()
{
logging.AddZLoggerStream(Stream.Null, options =>
{
options.UsePlainTextFormatter(formatter => formatter.SetPrefixFormatter($"{0} [{1}]", (template, info) => template.Format(info.Timestamp, info.LogLevel)));
options.UsePlainTextFormatter(formatter => formatter.SetPrefixFormatter($"{0} [{1}]", (in MessageTemplate template, in LogInfo info) => template.Format(info.Timestamp, info.LogLevel)));
});
});
disposables.Add(zLoggerFactory);
Expand Down
2 changes: 1 addition & 1 deletion sandbox/Benchmark/Benchmarks/WritePlainTextToConsole.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public void SetUpLogger()
console.UsePlainTextFormatter(formatter =>
{
formatter.SetPrefixFormatter($"{0} [{1}]",
(template, info) => template.Format(info.Timestamp, info.LogLevel));
(in MessageTemplate template, in LogInfo info) => template.Format(info.Timestamp, info.LogLevel));
});
});
});
Expand Down
2 changes: 1 addition & 1 deletion sandbox/Benchmark/Benchmarks/WritePlainTextToFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public void SetUpLogger()
options.UsePlainTextFormatter(formatter =>
{
formatter.SetPrefixFormatter($"{0} [{1}]",
(template, info) => template.Format(info.Timestamp, info.LogLevel));
(in MessageTemplate template, in LogInfo info) => template.Format(info.Timestamp, info.LogLevel));
});
});
});
Expand Down
27 changes: 15 additions & 12 deletions sandbox/ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,28 @@
using var factory = LoggerFactory.Create(logging =>
{
// Add ZLogger provider to ILoggingBuilder
//logging.AddZLoggerConsole(options =>
//{
// options.UsePlainTextFormatter(formatter =>
// {
// // formatter.SetPrefixFormatter($"foo", (template, info) => info.CallerLineNumber
// });
//});
logging.AddZLoggerConsole(options =>
{
options.UsePlainTextFormatter(formatter =>
{
formatter.SetPrefixFormatter($"foo", (in MessageTemplate template, in LogInfo info) => template.Format());
//MessageTemplate
// LogInfo
//formatter.SetPrefixFormatter($"foo", (template, info) => template.Format());
});
});
//// Output Structured Logging, setup options
//logging.AddZLoggerConsole(options => options.UseJsonFormatter(formatter =>
//{
// formatter.IncludeProperties = IncludeProperties.ParameterKeyValues | IncludeProperties.MemberName | IncludeProperties.FilePath | IncludeProperties.LineNumber;
//}));
logging.AddZLoggerConsole(options =>
{
options.InternalErrorLogger = ex => Console.WriteLine(ex);
options.UseFormatter(() => new CLEFMessageTemplateFormatter());
});
//logging.AddZLoggerConsole(options =>
//{
// options.InternalErrorLogger = ex => Console.WriteLine(ex);
// options.UseFormatter(() => new CLEFMessageTemplateFormatter());
//});
});
Expand Down
2 changes: 1 addition & 1 deletion sandbox/ConsoleApp/SampleFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public static ZLoggerOptions UseCloudLoggingJsonFormat(this ZLoggerOptions optio
var eventId = Encode("eventId");
var userId = Encode("userId");
formatter.AdditionalFormatter = (writer, logInfo) =>
formatter.AdditionalFormatter = (Utf8JsonWriter writer, in LogInfo logInfo) =>
{
writer.WriteStartObject(labels);
writer.WriteString(category, logInfo.Category.JsonEncoded);
Expand Down
4 changes: 3 additions & 1 deletion src/ZLogger.Unity/Assets/Sample/SampleBehaviour.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ void Start()

var name = "Hoge";
var id = 12345;


logger.ZLogInformation($"with context {name}", this);

logger.Log(LogLevel.Information, $"Log");
logger.LogInformation($"LogInformation");

Expand Down
2 changes: 1 addition & 1 deletion src/ZLogger.Unity/Assets/Tests/FormatTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public void FormatLogEntry_CustomMetadata()
options.UseJsonFormatter(formatter =>
{
formatter.AdditionalFormatter = (writer, _) =>
formatter.AdditionalFormatter = (Utf8JsonWriter writer, in LogInfo _) =>
{
writer.WriteString(hashProp, sourceCodeHash);
};
Expand Down
40 changes: 20 additions & 20 deletions src/ZLogger.Unity/UserSettings/Layouts/default-2022.dwlt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ MonoBehaviour:
width: 2738
height: 2053
m_ShowMode: 4
m_Title: Project
m_Title: Console
m_RootView: {fileID: 2}
m_MinSize: {x: 875, y: 300}
m_MaxSize: {x: 10000, y: 10000}
Expand Down Expand Up @@ -119,7 +119,7 @@ MonoBehaviour:
m_MinSize: {x: 400, y: 100}
m_MaxSize: {x: 32384, y: 16192}
vertical: 0
controlID: 113
controlID: 189
--- !u!114 &6
MonoBehaviour:
m_ObjectHideFlags: 52
Expand All @@ -144,7 +144,7 @@ MonoBehaviour:
m_MinSize: {x: 300, y: 100}
m_MaxSize: {x: 24288, y: 16192}
vertical: 1
controlID: 114
controlID: 190
--- !u!114 &7
MonoBehaviour:
m_ObjectHideFlags: 52
Expand All @@ -170,7 +170,7 @@ MonoBehaviour:
m_MinSize: {x: 300, y: 50}
m_MaxSize: {x: 24288, y: 8096}
vertical: 0
controlID: 42
controlID: 170
--- !u!114 &8
MonoBehaviour:
m_ObjectHideFlags: 52
Expand All @@ -190,8 +190,8 @@ MonoBehaviour:
y: 0
width: 803
height: 775
m_MinSize: {x: 201, y: 221}
m_MaxSize: {x: 4001, y: 4021}
m_MinSize: {x: 200, y: 200}
m_MaxSize: {x: 4000, y: 4000}
m_ActualView: {fileID: 14}
m_Panes:
- {fileID: 14}
Expand Down Expand Up @@ -242,8 +242,8 @@ MonoBehaviour:
y: 0
width: 532
height: 775
m_MinSize: {x: 202, y: 221}
m_MaxSize: {x: 4002, y: 4021}
m_MinSize: {x: 200, y: 200}
m_MaxSize: {x: 4000, y: 4000}
m_ActualView: {fileID: 16}
m_Panes:
- {fileID: 16}
Expand All @@ -259,7 +259,7 @@ MonoBehaviour:
m_Enabled: 1
m_EditorHideFlags: 1
m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0}
m_Name: ProjectBrowser
m_Name: ConsoleWindow
m_EditorClassIdentifier:
m_Children: []
m_Position:
Expand All @@ -268,14 +268,14 @@ MonoBehaviour:
y: 775
width: 2097
height: 1228
m_MinSize: {x: 231, y: 271}
m_MaxSize: {x: 10001, y: 10021}
m_ActualView: {fileID: 17}
m_MinSize: {x: 101, y: 121}
m_MaxSize: {x: 4001, y: 4021}
m_ActualView: {fileID: 13}
m_Panes:
- {fileID: 17}
- {fileID: 13}
m_Selected: 0
m_LastSelected: 1
m_Selected: 1
m_LastSelected: 0
--- !u!114 &12
MonoBehaviour:
m_ObjectHideFlags: 52
Expand Down Expand Up @@ -895,7 +895,7 @@ MonoBehaviour:
scrollPos: {x: 0, y: 0}
m_SelectedIDs:
m_LastClickedID: 0
m_ExpandedIDs: aaf5ffff
m_ExpandedIDs: 0af9ffff
m_RenameOverlay:
m_UserAcceptedRename: 0
m_Name:
Expand Down Expand Up @@ -979,9 +979,9 @@ MonoBehaviour:
m_IsLocked: 0
m_FolderTreeState:
scrollPos: {x: 0, y: 0}
m_SelectedIDs: c4450000
m_LastClickedID: 17860
m_ExpandedIDs: 00000000884500008a45000090450000a2450000c445000000ca9a3bffffff7f
m_SelectedIDs: 4e450000
m_LastClickedID: 17742
m_ExpandedIDs: 00000000464500004a45000000ca9a3bffffff7f
m_RenameOverlay:
m_UserAcceptedRename: 0
m_Name:
Expand Down Expand Up @@ -1009,7 +1009,7 @@ MonoBehaviour:
scrollPos: {x: 0, y: 0}
m_SelectedIDs:
m_LastClickedID: 0
m_ExpandedIDs: 00000000884500008a450000
m_ExpandedIDs: 000000004645000000ca9a3bffffff7f
m_RenameOverlay:
m_UserAcceptedRename: 0
m_Name:
Expand All @@ -1036,7 +1036,7 @@ MonoBehaviour:
m_ListAreaState:
m_SelectedInstanceIDs:
m_LastClickedInstanceID: 0
m_HadKeyboardFocusLastEvent: 1
m_HadKeyboardFocusLastEvent: 0
m_ExpandedInstanceIDs: c6230000
m_RenameOverlay:
m_UserAcceptedRename: 0
Expand Down
10 changes: 6 additions & 4 deletions src/ZLogger/Formatters/PlainTextZLoggerFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

namespace ZLogger.Formatters
{
public delegate void MessageTemplateFormatter(in MessageTemplate template, in LogInfo info);

public class PlainTextZLoggerFormatter : IZLoggerFormatter
{
static readonly byte[] newLine = Encoding.UTF8.GetBytes(Environment.NewLine);
Expand All @@ -12,17 +14,17 @@ public class PlainTextZLoggerFormatter : IZLoggerFormatter
Action<IBufferWriter<byte>, Exception> exceptionFormatter = DefaultExceptionLoggingFormatter;

MessageTemplateHolder? prefixTemplate;
Action<MessageTemplate, LogInfo>? prefixFormatter;
MessageTemplateFormatter? prefixFormatter;
MessageTemplateHolder? suffixTemplate;
Action<MessageTemplate, LogInfo>? suffixFormatter;
MessageTemplateFormatter? suffixFormatter;

public void SetPrefixFormatter(MessageTemplateHandler format, Action<MessageTemplate, LogInfo> formatter)
public void SetPrefixFormatter(MessageTemplateHandler format, MessageTemplateFormatter formatter)
{
this.prefixTemplate = format.GetTemplate();
this.prefixFormatter = formatter;
}

public void SetSuffixFormatter(MessageTemplateHandler format, Action<MessageTemplate, LogInfo> formatter)
public void SetSuffixFormatter(MessageTemplateHandler format, MessageTemplateFormatter formatter)
{
this.suffixTemplate = format.GetTemplate();
this.suffixFormatter = formatter;
Expand Down
4 changes: 3 additions & 1 deletion src/ZLogger/Formatters/SystemTextJsonZLoggerFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ JsonEncodedText LineNumber
);
}

public delegate void JsonLogInfoFormatter(Utf8JsonWriter jsonWriter, in LogInfo info);

public class SystemTextJsonZLoggerFormatter : IZLoggerFormatter
{
public JsonPropertyNames JsonPropertyNames { get; set; } = JsonPropertyNames.Default;
Expand All @@ -117,7 +119,7 @@ public class SystemTextJsonZLoggerFormatter : IZLoggerFormatter
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
};

public Action<Utf8JsonWriter, LogInfo>? AdditionalFormatter { get; set; }
public JsonLogInfoFormatter? AdditionalFormatter { get; set; }
public JsonEncodedText? PropertyKeyValuesObjectName { get; set; } // if null(default), non nested.
public IKeyNameMutator? KeyNameMutator { get; set; }
public bool UseUtcTimestamp { get; set; } // default is false, use Local.
Expand Down
4 changes: 2 additions & 2 deletions tests/ZLogger.Generator.Tests/AttributeTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public void Log()
{
using var _ = TestHelper.CreateLogger<AttributeTest>(LogLevel.Debug, options => options.UsePlainTextFormatter(formatter =>
{
formatter.SetPrefixFormatter($"{0}:", (template, info) => template.Format(info.LogLevel));
formatter.SetPrefixFormatter($"{0}:", (in MessageTemplate template, in LogInfo info) => template.Format(info.LogLevel));
}), out var logger, out var list);

ZeroCtor(logger, LogLevel.Debug, 10, 20);
Expand All @@ -70,7 +70,7 @@ public void Error()
{
using var _ = TestHelper.CreateLogger<AttributeTest>(LogLevel.Debug, options => options.UsePlainTextFormatter(formatter =>
{
formatter.SetPrefixFormatter($"{0}:", (template, info) => template.Format(info.Exception?.Message));
formatter.SetPrefixFormatter($"{0}:", (in MessageTemplate template, in LogInfo info) => template.Format(info.Exception?.Message));
formatter.SetExceptionFormatter((_, _) => { });
}), out var logger, out var list);

Expand Down
Loading

0 comments on commit cbed06c

Please sign in to comment.