serilog-contrib / Serilog.Sinks.Postgresql.Alternative

Serilog.Sinks.Postgresql.Alternative is a library to save logging information from https://github.com/serilog/serilog to https://www.postgresql.org/.
MIT License
67 stars 13 forks source link

How to add a custom column containing the name of the application? #60

Closed aminotran closed 1 year ago

aminotran commented 1 year ago

My application consists of a lot of small applications. I use your library to aggregate the application log of all of them into one place to monitor and analyze it. However, I don't know which small application the log is from. In your sample example there is information about the machine_name column, however all of my small apps are running on the same server so it doesn't make sense.

Each of my small apps has a unique name, and I want it to display that name for each record that serilog writes to the database on the app_name column.

Please guide me to do this. Thank you!

SeppPenner commented 1 year ago

Does each application have an individual configuration of the sink? And do you configure the sink by using A JSON file or within the code?

SeppPenner commented 1 year ago

Something like this should work:

const string TableName = "Logs2";
const string ConnectionString = "User ID=postgres;Password=postgres;Host=localhost;Port=5432;Database=Serilog";
const string appName = "TestApp1";

var columnProps = new Dictionary<string, ColumnWriterBase>
{
    { "Message", new RenderedMessageColumnWriter() },
    { "MessageTemplate", new MessageTemplateColumnWriter() },
    { "Level", new LevelColumnWriter(true, NpgsqlDbType.Text) },
    { "RaiseDate", new TimestampColumnWriter() },
    { "Exception", new ExceptionColumnWriter() },
    { "Properties", new LogEventSerializedColumnWriter() },
    { "AppName", new PropertiesColumnWriter(NpgsqlDbType.Text) }
};

var logger = new LoggerConfiguration()
    .WriteTo
    .PostgreSQL(ConnectionString, TableName, columnProps, needAutoCreateTable: true)
    .CreateLogger();

logger.Information("{AppName}: Some message", appName);

and take a look at https://github.com/saleem-mirza/serilog-enrichers-context to avoid adding the app name all the time to all messages manually.