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

Sink silently failing in Console app. #17

Open
granicus422 opened this issue May 26, 2020 · 1 comment
Open

Sink silently failing in Console app. #17

granicus422 opened this issue May 26, 2020 · 1 comment

Comments

@granicus422
Copy link

I have both a web app and a console app (both .NET Core 3.1) that I am trying to add the MySql sink to. They share identical appsettings.json files, and the standard console sink works on both. However, I can only see logs written through the MySql sink when running the web app. My console app only logs to the console sink, not the MySql sink. I enabled the SelfLog to show the output to console, and it shows "Sending batch of 1 logs" but I see nothing else to indicate an error in the MySql sink. The only difference is in the inherent difference in setting up a logger for a console app vs the web host.

I have tried "manually" configuring the sinks instead of reading from appsettings.json, and I get the exact same output (logs write to console, not to MySql). My console app logic is below. Again, this same configuration works in the web app, so there is either an issue with my console logic, an issue in the Sink, or an error happening inside the sink (like permissions?) that is not getting surfaced through the SelfLog. What am I missing?

namespace Engine
{
    class Program
    {
        private static Dictionary<string,string> ArgDict = new Dictionary<string, string>();

        static void Main(string[] args)
        {
            Console.WriteLine(DateTime.Now.ToLongTimeString());
            Console.WriteLine(args.Length);

#if DEBUG
            Array.Resize(ref args, 4);
            args[0] = "Engine.exe";
            args[1] = "-assoc";
            args[2] = "0";
            args[3] = "-temp";
#endif
 
            for (int i = 0; i <= args.Length - 1; i++)
            {
                if (args[i].Substring(0, 1) == "-")
                {
                    if (i < args.Length - 1 && args[i + 1].Substring(0, 1) != "-")
                    {
                        ArgDict.Add(args[i].ToLower(), args[i + 1].ToLower());
                    }
                    else
                    {
                        ArgDict.Add(args[i].ToLower(), "");
                    }
                }
            }

                var services = ConfigureServices();

             var serviceProvider = services.BuildServiceProvider();

            ServiceActivator.Configure(serviceProvider);

            // calls the Run method in App, which is replacing Main
            serviceProvider.GetService<App>().Run(ArgDict);

            Console.WriteLine(DateTime.Now.ToLongTimeString());
        }
        private static IServiceCollection ConfigureServices()
        {
            var services = new ServiceCollection();

            var config = LoadConfiguration();
           
            var serilogLogger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration: config)
                //.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}")
                //.WriteTo.MySQL("Datasource=localhost;database=mydb;uid=mysqluser;pwd=mysqlpassword;","serilog")
                .CreateLogger();
            Serilog.Debugging.SelfLog.Enable(Console.Error);
            serilogLogger.Information("test console log");
            services.AddLogging(configure => configure.AddSerilog(logger:serilogLogger));
            Log.Logger = serilogLogger;

            services.AddTransient<App>();

            return services;
        }

        public static IConfiguration LoadConfiguration()
        {
            string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            Console.WriteLine("Environment: {0}", environment);

            // Set up configuration sources.
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{environment}.json");
#if DEBUG
            builder.AddUserSecrets<Program>();
#endif

            return builder.Build();
        }
    }
}

image

@Davidos533
Copy link

Davidos533 commented Feb 20, 2022

FINALLY
Solution was very intresting my friends,
In problem write: "I have both a web app and a console app"

When you starting test console app often this app works some seconds, and closes
ASP net apps in debug mode, works when you browser opened (by ISS), and that longer than test-console app works
i just added Console.ReadLine(); in end of console app and wait a long time (5-10 sec) and with Serilog.Debugging.SelfLog.Enable(Console.Error);
i saw in console message, like:
2022-02-20T21:19:54.5456269Z Sending batch of 2 logs
and in DB was entries!!!

I saw source code, and i think Serilog worls with DB MySQL slowly, because there using StringBuilder() constructions to build query to DB and queryExec, it slowly therefore you app need work longer than 4 seconds))
(if I'm wrong, write to me)

MY FINALLY WORKS CODE:
C#

Serilog.Debugging.SelfLog.Enable(Console.Error);

                // make logger
                // create logger configuration
                Log.Logger = new LoggerConfiguration()

                    // read configuration from builded config
                    // add sinks ...
                    .ReadFrom.Configuration(builder.Build())
                    // enrich with logger context
                    .Enrich.FromLogContext()
                    // create logger and save it in Log.Logger
                    .CreateLogger();

                // log info by created logger
                Log.Logger.Information("Application Starting");
                ...
                // Program need time to write in DB
                Console.ReadLine();

JSON

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.MySQL" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Information",
        "System": "Warning"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "MySQL",
        "Args": {
          "connectionString": "server=localhost;uid=**username**;pwd=**password**;database=**databasename**;SslMode=none"
        }
      }
    ]
  }
}

Hello, i have a same problem with mysql and serilog, i try to find solution
I see this problem was posted for a long time ago

You switch on: Serilog.Debugging.SelfLog.Enable(Console.Error);
after var serilogLogger = new LoggerConfiguration()

you should switch on it before serilog configuration, and you will see process of configuring, of try to connect and create table in mysql

My problem was (Console output):

Server=localhost;Database=mydatabasename;Uid=username;Pwd=password;SslMode=none
2022-02-20T19:31:18.9480604Z The host 127.0.0.1 does not support SSL connections.
2022-02-20T19:31:18.9495358Z Object reference not set to an instance of an object.
[22:31:18 INF] Application Starting

Read more and interesting

  1. My first problem is SslMode, i didn't set SslMode=none
    when i set SslMode=none, i didn't see anything in console, i saw in my MySQL server by phpAdmin (MAMP) and in my DB i saw table, Great!!!
    But when i saw in table, i was disappointed, table was without entries
    I started program again and again, i searched all google, but not fint solution, then i go to Seilog git hub, and find https://github.com/saleem-mirza/serilog-sinks-mysql

It was source code, i compiled my project with this nuget:

    <PackageReference Include="MySql.Data" Version="8.0.28" />
    <PackageReference Include="Serilog" Version="2.10.0" />
    <PackageReference Include="Serilog.Extensions.Hosting" Version="4.2.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />

i had this c# code:

  Serilog.Debugging.SelfLog.Enable(Console.Error);

                // make logger
                // create logger configuration
                Log.Logger = new LoggerConfiguration()

                    // read configuration from builded config
                    // add sinks ...
                    .ReadFrom.Configuration(builder.Build())
                    // enrich with logger context
                    .Enrich.FromLogContext()

                    // Warning! I am uisng bind to MySQL here, because if i want use it in json config file i need to add  assembly  ...
                    // ... but i didn't have assembly because i use source code of MySQL Serilog
                    .WriteTo.MySQL("server=localhost;uid=username;pwd=password;database=databasename;SslMode=none")
                    // create logger and save it in Log.Logger
                    .CreateLogger();

                // log info by created logger
                Log.Logger.Information("Application Starting");

if it console app, you soud add Console.ReadLine(); in end, therefore you program can ends before log in DataBase

i had this json configuration file

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console"],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Information",
        "System": "Warning"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "MySQL",
        "Args": {
          "connectionString": "server=localhost;uid=username;pwd=password;database=databasename;SslMode=none"
        }
      }
    ]
  }
}

went through the code with a debugger (in some places i needed to use only steps without F5, program can jump around MySQL log Query Code) and i find exception in sending message like: "Unknown column 'Template' in 'field' list"
it was bacause table what i cretate by nuget packege Seilog.Sink.MySQL didn't have column with name 'Template', i drop old table and restart app, and i saw log entry in db!! But this works only when i use debugger with (f10,f11) in places with insert query of Serilog.Sink.MySQL, else i got message in console:

image

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

2 participants