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

MessageTemplate Property #11

Open
CraigKennedy opened this issue Mar 6, 2020 · 2 comments
Open

MessageTemplate Property #11

CraigKennedy opened this issue Mar 6, 2020 · 2 comments

Comments

@CraigKennedy
Copy link

Is there any way to get the message template sent along (may as a label?)? I would like to filter in loki based on all the entries with a specific Message Template

@m-mccormick
Copy link

Dropping two classes in your project should do the trick for the time being:

using System;

namespace MessagTemplateSerilog
{
    using Serilog;
    using Serilog.Configuration;
    using Serilog.Core;
    using Serilog.Events;
    using Serilog.Sinks.Loki;

    class Program
    {
        static void Main(string[] args)
        {
            var log = new LoggerConfiguration().
                      Enrich.WithMessageTemplate().
                      WriteTo.LokiHttp(new NoAuthCredentials("http://localhost:3100")).CreateLogger();
            
            log.Information("An int {name} with a value {value}", "myIntName", 8);
            log.Dispose();
        }
    }

    public class MessageTemplateEnricher : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            LogEventProperty property = propertyFactory.CreateProperty("Message_Template", logEvent.MessageTemplate.Text);
            logEvent.AddPropertyIfAbsent(property);
        }
    }

    public static class MessageTemplateEnricherExtensions
    {
        public static LoggerConfiguration WithMessageTemplate(
            this LoggerEnrichmentConfiguration enrichmentConfiguration)
        {
            if (enrichmentConfiguration == null)
                throw new ArgumentNullException(nameof(enrichmentConfiguration));

            return enrichmentConfiguration.With<MessageTemplateEnricher>();
        }
    }
}

Keep in mind that you'll have to use a regex search (using .) since loki doesn't like the { and } characters in queries, so you won't be able to search for an exact match but it should be close enough.

{Message_Template=~"An int .name. with a value .value."}

@qiqistart
Copy link

I’d like to know that how to use serilog.loki to establish a customizing client to make an index for writing logs as Elasticsearch.?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants