Movatterモバイル変換


[0]ホーム

URL:


Loading

Elastic.Extensions.Logging

Elastic logger provider for Microsoft.Extensions.Logging.

Writes direct to Elasticsearch using the [Elastic Common Schema (ECS)]Elastic Common Schema (ECS)), with semantic logging of structured data from message and scope values. The results can be viewed and queried in the Kibana console.

Add a reference to theElastic.Extensions.Logging package:

<PackageReference Include="Elastic.Extensions.Logging" Version="8.6.0" />

Then, add the provider to the loggingBuilder during host construction, using the provided extension method.

using Elastic.Extensions.Logging;// ...    .ConfigureLogging((hostContext, loggingBuilder) =>    {        loggingBuilder.AddElasticsearch();    })

The default configuration will write to a local Elasticsearch running athttp://localhost:9200/.

Once you have sent some log event, open Kibana (e.g.http://localhost:5601/) and define an index pattern for "dotnet-*" with the time filter "@timestamp".

You can then discover the log events for the index. Some useful columns to add arelog.level,log.logger,event.code,message,tags, andprocess.thread.id.

If you are running multiple applications or on multiple servers, you might want to includeservice.type,service.version, andhost.hostname.

Additional fields are defined below, and all individual message and scope values are logged aslabels.* custom key/value pairs, e.g.labels.CustomerId.

For deployment you will usually want to override the configuration with your actual server location(s). The other useful value to configure is a tag for the environment, e.g. Development/Staging/Production.

{  "Logging": {    "Elasticsearch": {      "NodeUris": [ "https://elastic-staging.example.com:9200" ],      "Tags": [ "Staging" ]    }  }}

NOTE: You don’t need any configuration to just use a local Elasticsearch instance, as it defaults tohttp://localhost:9200/.

The logger provider will be automatically configured with any logging settings under the aliasElasticsearch.

The following default settings are used.

{  "Logging": {    "Elasticsearch": {      "IncludeHost": true,      "IncludeProcess": true,      "IncludeScopes": true,      "IncludeUser": true,      "Index": "dotnet-{0:yyyy.MM.dd}",      "IndexOffset": null,      "IsEnabled": true,      "ListSeparator": ", ",      "MapCorrelationValues": true,      "Tags": [],      "ShipTo": {        "NodePoolType": "SingleNode",        "NodeUris": [ "http://localhost:9200" ]      }    }  }}
SettingTypeDescription
IncludeHostbooleanDefaulttrue; set tofalse to disable logging host values.
IncludeProcessbooleanDefaulttrue; set tofalse to disable logging process values.
IncludeScopesbooleanDefaulttrue; set tofalse to disable logging scope values.
IncludeUserbooleanDefaulttrue; set tofalse to disable logging user details.
IndexformatFormat string used to generate the Elasticsearchindex, using the current timestamp. Default isdotnet-{0:yyyy.MM.dd}.
IndexOffsettimespanOverride to set the offset used to generate theindex. Default value isnull, which uses the system local offset; use"00:00&" for UTC.
IsEnabledbooleanDefaulttrue; set tofalse to disable the logger.
ListSeparatorstringSeparator to use forIEnumerable inlabels.* values. Default is", ".
TagsarrayAdditional tags to include in the message. Useful to specify the environment or other details, e.g.[ "Staging", "Priority"]

The ShipTo settings can have the following properties, depending on the type of connection pool.

SettingTypeDescription
ApiKeystringAPI Key, where connection pool type is Cloud, and authenticating via API Key.
CloudIdstringCloud ID, where connection pool type is Cloud.
NodePoolTypeenumDefault isSinglenode, orSniffing for multiple nodes, orCloud ifCloudId is provided. Other supported values areStatic orSticky.
NodeUrisarrayURI(s) of the Elasticsearch nodes to connect to. Default is a single node[ "http://localhost:9200" ]
PasswordstringPassword, where connection pool type is Cloud, and authenticating via username/password.
UsernamestringUsername, where connection pool type is Cloud, and authenticating via username/password.

If you want to configure from a different section, it can be configured manually:

.ConfigureLogging((hostContext, loggingBuilder) =>{    loggingBuilder.AddElasticsearch(options =>        hostContext.Configuration.Bind("Logging:CustomElasticsearch", options));})

Configuration can, of course, also be done in code, e.g. to add the environment as a tag.

IfCloudId is provided, theConnectionPoolType defaults toCloud:

{  "Logging": {    "Elasticsearch": {      "ShipTo": {        "CloudId": "12345",        "ApiKey": "abcdef"      }    }  }}

Log messages sent to Elasticsearch follow the [Elastic Common Schema (ECS)]Elastic Common Schema (ECS)).

The_source field is the message sent from the LoggerProvider, along with the_index and_id (a GUID).

{  "_index": "dotnet-2020.04.12",  "_type": "_doc",  "_id": "563503a8-9d10-46ff-a09f-c6ccbf124db9",  "_version": 1,  "_score": null,  "_source": {    "MessageTemplate": "Unexpected error processing customer {CustomerId}.",    "Scopes": [      "IP address 2001:db8:85a3::8a2e:370:7334",      "PlainScope"    ],    "agent": {      "version": "1.0.0+bd3ad6",      "type": "Elastic.Extensions.Logging.LoggerProvider"    },    "ecs": {      "version": "1.5.0"    },    "error": {      "message": "Calculation error",      "type": "System.Exception",      "stack_trace": "System.Exception: Calculation error\n ---> System.DivideByZeroException: Attempted to divide by zero.\n   at HelloElasticsearch.Worker.ExecuteAsync(CancellationToken stoppingToken) in /home/sly/Code/essential-logging/examples/HelloElasticsearch/Worker.cs:line 80\n   --- End of inner exception stack trace ---\n   at HelloElasticsearch.Worker.ExecuteAsync(CancellationToken stoppingToken) in /home/sly/Code/essential-logging/examples/HelloElasticsearch/Worker.cs:line 84"    },    "event": {      "code": "5000",      "action": "ErrorProcessingCustomer",      "severity": 3    },    "host": {      "os": {        "platform": "Unix",        "full": "Linux 4.15.0-91-generic #92-Ubuntu SMP Fri Feb 28 11:09:48 UTC 2020",        "version": "4.15.0.91"      },      "hostname": "VUB1804",      "architecture": "X64"    },    "log": {      "level": "Error",      "logger": "HelloElasticsearch.Worker"    },    "process": {      "thread": {        "id": 10      },      "pid": 25982,      "name": "HelloElasticsearch"    },    "service": {      "type": "HelloElasticsearch",      "version": "1.0.0"    },    "user": {      "id": "sgryphon+es@live.com",      "name": "sly",      "domain": "VUB1804"    },    "@timestamp": "2020-04-13T21:25:22.3352989+10:00",    "tags": [      "Development"    ],    "labels": {      "ip": "2001:db8:85a3::8a2e:370:7334",      "CustomerId": "12345"    },    "message": "Unexpected error processing customer 12345.",    "trace": {      "id": "c20bde1071f7cf4e9a6f368c824e05f7"    },    "transaction": {      "id": "92ba5ee64d963746"    }  },  "fields": {    "@timestamp": [      "2020-04-13T11:25:22.335Z"    ]  },  "sort": [    1586777122335  ]}
FieldTypeDescription
@timestampdateDateTimeOffset when the message was logged, including local offset.
messagestringThe formatted log message and arguments.
tagsarrayCustom tags from configuration, e.g.[ "Staging", "Priority" ]. Can have multiple values.
event.actionstringThe name of the logged EventId, e.g.ErrorProcessingCustomer.
event.codestringThe numeric value (as a string) of the EventId, e.g.5000.
event.severitylongThe syslog severity corresponding to the log level, 2 = critical, 3 = error, 4 = warning, 6 = information, 7 = debug and trace. (Also used in the Systemd format of ConsoleLoggerProvider)
log.levelstringThe log level:Critical,Error,Warning,Information,Debug, orTrace.
log.loggerstringThe category name (namespace and class) of the logger, e.g.HelloElasticsearch.Worker.

Theevent.severity field is numeric and can be used to order events by level, e.g. Kibana queryevent.severity &lt;= 4 will get all messages that have log levelWarning or worse.

If the log message includes an exception, the details are reported in the error fields.

FieldTypeDescription
error.messagestringTheMessage property of any exception.
error.stack_tracestringFull details of the exception,Exception.ToString(), including the stack trace and the stack trace of any inner exceptions.
error.typestringThe type of the error message, e.g.System.DivideByZeroException

Following the ECS conventions, these use alternative Title casing, to identify them as non-standard fields.

FieldTypeDescription
MessageTemplatestringThe original message template, e.g. "Unexpected error processing customer{{CustomerId}}."
ScopesarrayArray of string formatted scope values, in the order added.
FieldTypeDescription
labels.*stringCustom key/value pairs of all named parameter values and named scope values. All values are strings (no nested objects).

Label values can be accessed by their key, for example if the message, or scope, includes a parameter CustomerId, then the value will be logged aslabels.CustomerId can be searched in Kibana using "labels.CustomerId: 12345".

Example:

The following will generate two labels,labels.EndTime from the message andlabels.CustomerId from the scope:

using (_logger.BeginScope("{CustomerId}", customerId)){  _logger.LogWarning("End of processing reached at {EndTime}.", end);}

Labels are taken from the message (state) and any scope values (may be disabled via the configuration options). In Microsoft.Extensions.Logging an internal FormattedLogValues is used in the ILogger overloads for log levels and scopes; it implements theIEnumerable&lt;KeyValuePair&lt;string,object&gt;&gt; interface that is used to extract the individual parameter values.

Thelabels property in ECS should not contain nested objects, so values are converted to keyword strings. For most objects this is just calling ToString(), with specific formats for some types, e.g. calling string on a list is usually not very useful, so the contents of the list is logged instead.

Labels value formatting

TypeFormatting
byteHex, e.g. "9A"
byte[]Prefixed hex, e.g. "0x12789AF0"
DateTimeOffsetISO format, e.g. "2020-01-02T03:04:05.000000+06:00"
DateTimeIn most casesDateTimeOffset should be used instead (1). WhereDateTime is used for date only (with no time component), it is formatted as a date, e.g. "2020-01-02". If it has a time component, the roundtrip ("o") format is used.
IEnumerableValues separated by ", " (configurable)
IDictionary<string, object>A string containing key value pairs, e.g.token="0x12789AF0" count="5"
other valuesThe result ofToString(), including scalar values, e.g. the number5.3 is logged as the string "5.3"

**(1) Seehttps://docs.microsoft.com/en-us/dotnet/standard/datetime/choosing-between-datetime**

These identify the version of the logger provider being used.

FieldTypeDescription
agent.typestringName of the logger provider assembly,Elastic.Extensions.Logging.LoggerProvider.
agent.versionstringInformational version number of the logger assembly, e.g.1.1.1+bd3ad63.
ecs.versionstringVersion of ECS standard used, currently1.5.

This identifies the application/service that is running and generating the logs.

The values are pulled from the entry assemb,Assembly.GetEntryAssembly(), using theName andAssemblyInformationalVersionAttribute values (if informational version is not set it falls back to assemblyVersion).

FieldTypeDescription
service.typestringName of the entry assembly,HelloElasticsearch.
service.versionstringInformational version number of the entry assembly, e.g.1.2.0-beta.1+79d095a.

Note: You should be using a build process that sets the assembly informational version correctly. e.g. If you have a dotnet project using git you can install the local toolGitVersion.Tool, and use it to automatically generate semantic version numbers from the git branch information.

To install the tool:

dotnet new tool-manifestdotnet tool install GitVersion.Tool

Then use the tool to create a semantic version number that can be used in your build process:

dotnet tool restoredotnet gitversion
FieldTypeDescription
trace.idstringCross-service trace correlation identifier. FromActivity.Current.RootId fromSystem.Diagnostics, with a fallback toCorrelationManager.ActivityId. Can be overridden by a message or scope valuetrace.id.
transaction.idstringTransaction for this service, e.g. individual request identifier. If in W3C format, parse out the SpanId fromActivity.Current.Id fromSystem.Diagnostics, otherwise just use the fullActivity.Current.Id (e.g. if hierarchical). Can be overridden by message or scope valuetransaction.id.

ASP.NET will automatically pass correlation identifiers between tiers; from 3.0 it also supports the W3C Trace Context standard (https://www.w3.org/TR/trace-context/).

The value ofActivity.Current.RootId is used as the cross-service identifier (in W3C format this is the Trace ID), if in W3C format the Span ID portion ofActivity.Current.Id is used for the transaction, otherwise the full value is used (this is consistent with the way ASP.NET works).

It is recommended to turn on W3C format, for compatibility with other systems:

Activity.DefaultIdFormat = ActivityIdFormat.W3C;
Note

Can be disabled via configuration.

FieldTypeDescription
host.architecturestringThe processor architecture, e.g. X64. Value ofRuntimeInformation.OSArchitecture.
host.hostnamestringThe computer name. Value ofEnvironment.MachineName.
host.os.fullstringFull description of the operation system. Value ofRuntimeInformation.OSDescription.
host.os.platformstringOperating system platform. Value ofEnvironment.OSVersion.Platform.
host.os.versionstringOperating system version. Value ofEnvironment.OSVersion.Version.
Note

Can be disabled via configuration.

FieldTypeDescription
process.namestringThe current process name. FromProcess.GetCurrentProcess().
process.pidlongThe current process ID. FromProcess.GetCurrentProcess().
process.thread.idlongCurrent thread ID. Value ofThread.CurrentThread.ManagedThreadId.
process.thread.namestringName of the thread. FromThread.CurrentThread.Name.
Note

Can be disabled via configuration.

FieldTypeDescription
user.domainstringThe current domain, either the machine name or a Windows domain. Value ofEnvironment.UserDomainName.
user.idstringCurrent user principal name, if set. Value ofThread.CurrentPrincipal.Identity.Name.
user.namestringThe current user. Value ofEnvironment.UserName.

[8]ページ先頭

©2009-2025 Movatter.jp