Serilog - C# - configuration

Markus Freitag 3,791 Reputation points
2023-06-07T17:42:15.3+00:00

Hello, As suggested by @Karen Payne MVP

https://betterstack.com/community/guides/logging/how-to-start-logging-with-serilog/

The global part of the project is probably already done by the library. I can call this via Log in every class. It looks good so far. Does not appear and color console does not work either. Maybe I need more

Install-Package Serilog
Install-Package Serilog.Sinks.Console
Install-Package Serilog.Sinks.File
Install-Package Serilog.Sinks.map

It is not viewable if I have never needed it. Maybe I need more.

My goal.

I am using a WinForm application and would like to open a console window with debugging in parallel. (For Debug, not for Release) // add console as logging target .WriteTo.Console() I use a WinForm application and want parallel a console open debugging.

Log File --- C:\Temp\Log\2023-06-07-MachineA.log If the file bigger than 25MByte use the next file.Log File I would like to write a new file from a certain size.

Inside file.

 Like this[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {Message}{NewLine}{Exception}
   But not work too. maybe mistake with [ ]  only open?

Why does ColoredConsole no longer work?

Can you please help me. Thank you in advance.

My code

using SerialLog.Core;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Sinks.SystemConsole;
using Serilog.Sinks.File;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SerialLog
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //Log.Logger = new LoggerConfiguration()
            //                // add console as logging target
            //                .WriteTo.Console()
            //                // set default minimum level
            //                .MinimumLevel.Debug()
            //                .CreateLogger();

            //var logger = new LoggerConfiguration()
            //Log.Logger = new LoggerConfiguration()
            //.WriteTo.ColoredConsole()
            //.WriteTo.RollingFile(@"C:\temp\Log-{Date}.txt")
            //.CreateLogger();

            Log.Logger = new LoggerConfiguration()
                           // add console as logging target
                           .WriteTo.Console()
                           // add a logging target for warnings and higher severity  logs
                           // structured in JSON format
                           .WriteTo.File(new JsonFormatter(),
                                         "important.json",
                                         restrictedToMinimumLevel: LogEventLevel.Warning)
                           // add a rolling file for all logs
                           //.WriteTo.File("all-.logs",
                           //.WriteTo.File("logs\\log.txt", rollingInterval: RollingInterval.Day)
                           //.WriteTo.File(@"C:\temp\log.txt", rollingInterval: RollingInterval.Day, fileSizeLimitBytes:200000)
                           //.WriteTo.File(@"C:\temp\log.txt", rollingInterval: RollingInterval.Day) //, fileSizeLimitBytes: 5000)
                           //.WriteTo.File(@"C:\temp\Log-{Timestamp:yyyy-MM-dd}.txt")

                           .WriteTo.Map("UtcDateTime", DateTime.UtcNow.ToString("yyyy-MM-dd"), (UtcDateTime, wt) => wt.File($@"C:\Temp\logs\log-{UtcDateTime}.txt"))
                           
                           // .WriteTo.File(@"C:\temp\Log-{Timestamp:yyyy-MM-dd}.txt", fileSizeLimitBytes: 20000000, outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{Level}] {Message}{NewLine}{Exception}")


                           .MinimumLevel.Debug()
                           .CreateLogger();

            //Log.Logger = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.File(@"C:\temp\Log-{Timestamp:yyyy-MM-dd}.txt", fileSizeLimitBytes: 20000000, outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{Level}] {Message}{NewLine}{Exception}").CreateLogger();

            //DateTime currentTime = DateTime.Now;
            //Log.Logger = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.File($"{currentTime.Year}-{currentTime.Month}-{currentTime.Day}.txt", fileSizeLimitBytes: 20000000, //outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{Level}] {Message}{NewLine}{Exception}").CreateLogger();

            //outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {Message}{NewLine}{Exception}").CreateLogger();
        }

        private void btnSerialLog_Click(object sender, EventArgs e)
        {
            // create 2 persons
            var person1 = new Person("Lothar", "FootballTeam11");
            var person2 = new Person("Michael", "Miller");
            // create 2 cars
            var car1 = new Car("Tesla Model S", 2020, person1);
            var car2 = new Car("Tesla Model X", 2020, person2);
            // logging
            Log.Verbose("Some verbose log");
            Log.Debug("Some debug log");
            Log.Information("Person1: {@person}", person1);
            Log.Information("Car2: {@car}", car2);
            Log.Warning("Warning accrued at {now}", DateTime.Now);
            Log.Error("Error accrued at {now}", DateTime.Now);
            Log.Fatal("Problem with car {@car} accrued at {now}", car1, DateTime.Now);

            for (int i = 0; i < 200000; i++)
                Log.Debug($"{i}, TEST");

            MessageBox.Show("Ready");
        }
    }
}






/// --------------------------------------------------------


using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SerialLog.Core
{
    public class Car
    {
        public string Model { get; set; }
        public int YearReleased { get; set; }
        public Person Owner { get; set; }

        public Car(string model, int yearReleased, Person owner)
        {
            Model = model;
            YearReleased = yearReleased;
            Owner = owner;

            Log.Debug("Created a car {@person} at {now}", this, DateTime.Now);
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public string LastName { get; set; }

        public Person(string name, string lastName)
        {
            Name = name;
            LastName = lastName;

            Log.Debug("Created a person {@person} at {now}", this, DateTime.Now);
        }
    }
}
Developer technologies | Windows Forms
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Karen Payne MVP 35,591 Reputation points Volunteer Moderator
    2023-06-08T11:39:23.7866667+00:00

    See the following project, and read the readme.md file


1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,591 Reputation points Volunteer Moderator
    2023-06-08T01:52:25.43+00:00

    The colored console only works for console and ASP.NET Core projects, not Windows Forms.

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.