Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

README (about options list) #121

Merged
merged 2 commits into from
Nov 30, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
337 changes: 323 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,32 +1,341 @@
ZLogger v2 ReadMe(TBD)


Getting Started
---

> PM> Install-Package [ZLogger](https://www.nuget.org/packages/ZLogger)


```csharp
using ZLogger;

var builder = Host.CreateApplicationBuilder();

builder.Logging
// optional(MS.E.Logging):clear default providers.
.ClearProviders()
.AddZLogger(zlogger =>
{
// Add to output to console
zlogger.AddConsole();

## ZLoggerOptions
// Add to output to the file
zlogger.AddFile("/path/to/file.log");

// Add to output the file that rotates at constant intervals.
zlogger.AddRollingFile((dt, x) => $"logs/{dt.ToLocalTime():yyyy-MM-dd}_{x:000}.log", x => x.ToLocalTime().Date, 1024);

// Add to output of simple rendered strings into memory. You can subscribe to this and use it.
zlogger.AddInMemory(processor =>
{
processor.MessageReceived += logMessageString => { /* ... */ };
});

// Add output to any steram (`System.IO.Stream`)
zlogger.AddStream(stream);

// Add custom output
zlogger.AddLogProcessor(new YourCustomLogExporter());

// Format as json
zlogger.AddConsole(options =>
{
options.UseJsonFormatter();
});

// Further settings
zlogger.AddConsole(options =>
{
// Enable scope
options.IncludeScopes = true;

//
options.TimeProvider =
});
});
```

```cs
using Microsoft.Extensions.Logging;
using ZLogger;

public class MyClass
{
readonly ILogger<MyClass> logger;

public MyClass(ILogger<MyClass> logger)
{
this.logger = logger;
}

public void Foo()
{
// Any variables...
var name = "Bill";
var city = "Kumamoto";
var age = 21;

// logging...
logger.ZLogInformation($"Hello, {name} lives in {city} {age} years old.");

// > text output:
// > Hello, Bill lives in Kumamoto 21 years old.
// >
// > json output:
// > {"Timestamp":"2023-11-30T17:28:35.869211+09:00","LogLevel":"Information","Category":"MyClass","Message":"Hello, Bill lives in Kumamoto 21 years old.","name":"Bill","city":"Kumamoto","age":21}


// Explicit property name
logger.ZLogInformation($"Hello, {("username", name)} id:{("id", 100)} {age} years old.");

// > text output:
// > Hello, Bill id:100 21 years old.
// >
// > json output:
// > {"Timestamp":"2023-11-30T17:28:35.869211+09:00","LogLevel":"Information","Category":"MyClass","Message":"Hello, Bill id:100 21 years old.","username":"Bill","id":100,"age":21}
}
}
```


ZLogger is built on top of [Microsoft.Extensions.Logging](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/), but adds `ZLog*` method family that are faster than basic Log calls.

All logging methods are completely similar as [Microsoft.Extensions.Logging.LoggerExtensions](https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loggerextensions), but it has **Z** prefix overload to avoid allocation of boxing.





The ZLog* method uses [InterpolatedStringHandler](https://learn.microsoft.com/ja-jp/dotnet/csharp/whats-new/tutorials/interpolated-string-handler) in .NET and prepare the template at compile time.

Note that the arguments always use `$""` literals.

Also, by default, expressions (variable names) in literals are parsed and used as keys for structured logging.
See [KeyNameMutator](#key-name-mutator)



TODO: Formatter Configurations....
----



### PlainTextZLoggerFormatter


| Name | Description |
|:-------------------------------------------------------------------------------------------------|:------------|
| `SetPrefixFormatter(MessageTemplateHandler format, Action<MessageTemplate, LogInfo> formatter)` | |
| `SetSuffixFormatter(MessageTemplateHandler format, Action<MessageTemplate, LogInfo> formatter)` | |
| `SetExceptionFormatter(Action<IBufferWriter<byte>, Exception> formatter)` | |


### SystemTextJsonZLoggerFormatter


| 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`. |
| `JsonEncodedText? PropertyKeyValuesObjectName` | |
| `IKeyNameMutator? KeyNameMutator` | |
| `bool UseUtcTimestamp` | |



TODO: LogInfo ?
---

| Name | Description |
|:----------------------------|:---------------------------------------------------------------------------------------------------------|
| `LogCategory Category` | The category name set for each logger. And holds JsonEncodedText and utf8 byte sequence representations. |
| `Timestamp Timestamp` | Timestamp |
| `LogLevel LogLevel` | LogLevel of `Microsoft.Extensions.Logging` |
| `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) |


TODO: KeyNameMutator
---


| Name | Description |
|:--------------------------------------|:----------------------------------------------------------------------------------------------------------|
| `LastMemberName` | Returns the last member name of the source. |
| `LowerFirstCharacter` | The first character converted to lowercase. |
| `UpperFirstCharacter` | The first character converted to uppercase. |
| `LastMemberNameLowerFirstCharacter` | Returns the last member name of the source with the first character converted to lowercase. |
| `LastMemberNameUpperFirstCharacter` | Returns the last member name of the source with the first character converted to uppercase. |


| Name | Description |
| ---- | ---- |
| `bool IncludeScopes { get; set; }` | Enable `ILogger.BeginScope`, default is `false`. |
| `TimeProvider? TimeProvider { get; set; }` | Gets or sets the time provider for the logger. The Timestamp of LogInfo is generated by TimeProvider's GetUtcNow() and LocalTimeZone when TimeProvider is set. The default value is null, which means use the system standard. |
| `Action<Exception>? InternalErrorLogger { get; set; }` | `InternalErrorLogger` is a delegate that is called when an exception occurs in the log writing process (such as a serialization error). The default value is `null`, which means errors are ignored. |
| `CreateFormatter()` | Create an formatter to use in ZLoggerProvider. |
| `UseFormatter(Func<IZLoggerFormatter> formatterFactory)` | |
| `UsePlainTextFormatter(Action<PlainTextZLoggerFormatter>? configure = null)` | |
| `UseJsonFormatter(Action<SystemTextJsonZLoggerFormatter>? configure = null)` | |

TODO:...
default formatter is PlaintTextFormatter.

## TODO: Formatter Configurations....


## TODO: ZLoggerBuilder

TODO: ZLoggerBuilder
----

ZLogger has the following providers.

| Type | Alias | Builder Extension |
|----------------------------------------|---------------------|-------------------|
| ZLoggerConsoleLoggerProvider | ZLoggerConsole | AddConsole |
| ZLoggerFileLoggerProvider | ZLoggerFile | AddFile |
| ZLoggerRollingFileLoggerProvider | ZLoggerRollingFile | AddRollingFile |
| ZLoggerStreamLoggerProvider | ZLoggerStream | AddStream |
| ZLoggerLogProcessorLoggerProvider | ZLoggerLogProcessor | AddLogProcessor |
| ZLoggerInMemoryProcessorLoggerProvider | ZLoggerInMemory | AddInMemory |


If you are using `Microsoft.Extensions.Configuration`, you can set the log level through configuration.
In this case, alias of Provider can be used. for example:

```json
{
"Logging": {
"LogLevel": {
"Default": "Information"
},
"ZLoggerConsoleLoggerProvider": {
"LogLevel": {
"Default": "Debug"
}
}
}
}
```

### Console

If you are using `ZLoggerConsoleLoggerProvider`, the following additional options are available

| Name | Description |
|:----------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------|
| `bool OutputEncodingToUtf8` | Set `Console.OutputEncoding = new UTF8Encoding(false)` when the provider is created. (default: true) | |
| `bool ConfigureEnableAnsiEscapeCode` | If set true, then configure console option on execution and enable virtual terminal processing(enable ANSI escape code). (default: false) |
| `LogLevel LogToStandardErrorThreshold` | If set, logs at a higher level than the value will be output to standard error. (default: LogLevel.None) |


```cs
builder.Logging
.ClearProviders()
.AddZLogger(zlogger =>
{
// Default
zlogger.AddConsole();

// Configure options
zlogger.AddConsole(options =>
{
options.LogToStandardErrorThreshold = LogLevel.Error;
});

// Configure options with service provider
zlogger.AddConsole((options, services) =>
{
options.TimeProvider = services.GetService<YourCustomTimeProvider>();
});
});
```

### File

```cs
builder.Logging
.ClearProviders()
.AddZLogger(zlogger =>
{
// Default
zlogger.AddFile(filePath);

// Configure options
zlogger.AddFile(filePath, options =>
{
// ...
});

// Configure options with service provider
zlogger.AddFile(filePath, (options, services) =>
{
// ...
});

// Configure file path dynamically
zlogger.AddFile((options, services) =>
{
return pathToFile;
});
});
```

### RollingFile

```csharp

```

### Stream

```cs
builder.Logging
.ClearProviders()
.AddZLogger(zlogger =>
{
// Default
zlogger.AddStream(stream);

// Configure options
zlogger.AddStream(stream, options =>
{
// ...
});

// Configure options with service provider
zlogger.AddFile(filePath, (options, services) =>
{
// ...
});

// Configure file path dynamically
zlogger.AddStream((options, services) =>
{
// ...
return yourCustomStream;
});
});

```

### In-Memory

todo

### Custom LogProcessor

todo


ZLoggerOptions
---


| Name | Description |
|:-----------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `bool IncludeScopes { get; set; }` | Enable `ILogger.BeginScope`, default is `false`. |
| `TimeProvider? TimeProvider { get; set; }` | Gets or sets the time provider for the logger. The Timestamp of LogInfo is generated by TimeProvider's GetUtcNow() and LocalTimeZone when TimeProvider is set. The default value is null, which means use the system standard. |
| `Action<Exception>? InternalErrorLogger { get; set; }` | `InternalErrorLogger` is a delegate that is called when an exception occurs in the log writing process (such as a serialization error). The default value is `null`, which means errors are ignored. |
| `CreateFormatter()` | Create an formatter to use in ZLoggerProvider. |
| `UseFormatter(Func<IZLoggerFormatter> formatterFactory)` | Set the formatter that defines the output format of the log. |
| `UsePlainTextFormatter(Action<PlainTextZLoggerFormatter>? configure = null)` | Use the built-in plain text formatter. |
| `UseJsonFormatter(Action<SystemTextJsonZLoggerFormatter>? configure = null)` | Use the built-in json formatter. (implementation of `System.Text.Json`) |

TODO:...
default formatter is PlaintTextFormatter.


# -----------------------------
Expand Down
Loading