Currently the application, Logger writes to the console by using the AddConsole() method.
How can it be set to write to a file?
for example to the directory "c:\workspace\TestProject\Log.txt"
logger = new LoggerFactory()
.AddConsole()
.CreateLogger("Msg");
I guess, you are using Microsoft.Framework.Logging
But out-of-the-box implementations are provided for basic console logging and a few other targets, you’ll need a logging back-end like Serilog or NLog to gain the kind of functionality you're requesting.
I would recommend you to use NLog (just personal preference)
Install-Package NLog
then add to your code
loggerFactory.AddNLog(new global::NLog.LogFactory());
https://github.com/aspnet/Logging/tree/dev/samples/SampleApp
http://nlog-project.org/
Related
I wanted my application to have capability of logging to a file, so I started to look for something more than default .NET Core 2.2 logging framework. I see that Serilog might do the job. However, I cannot find any document on how to setup Serilog in .NET Core Console application with Dependency Injection. All I see is ASP.NET materials, which is probably not what I need.
I started doing it myself. I installed (Nuget):
Serilog
Serilog.Extensions.Logging
Serilog.Sinks.File
Serilog.Sinks.Console (to use Serilog for all my logging)
I created an extension forServiceCollection
public static void AddLogging(this IServiceCollection services, Microsoft.Extensions.Logging.LogLevel logLevel)
{
var serilogLogger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("log.txt")
.CreateLogger();
services.AddLogging(builder =>
{
builder.SetMinimumLevel(logLevel);
builder.AddSerilog(logger: serilogLogger, dispose: true);
});
}
Logging works, however:
log level is not what I set it to. It seems that serilog is using INFO level, although I wanted to have DEBUG. Why isn't my setting respected? After all, I'm still using NET Core's logging framework, so I'm using it to setup the log level
am I actually doing this setup correctly? I am not really sure if dispose should be true. Generally, I want NET Core's Dependency Injection framework to take care of disposal of services.
I'm not sure about builder.SetMinimumLevel (it doesn't use the Serilog enum).
We set the logger level when creating the LoggerConfiguration object.
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Debug) // restricted... is Optional
(...)
.CreateLogger();
BTW. It's worth pointing out the following section from Configuration Basics
Logger vs. sink minimums - it is important to realize that the logging level can only be raised for sinks, not lowered. So, if the logger's MinimumLevel is set to Information then a sink with Debug as its specified level will still only see Information level events. This is because the logger-level configuration controls which logging statements will result in the creation of events, while the sink-level configuration only filters these. To create a single logger with a more verbose level, use a separate LoggerConfiguration.
I'm not sure about builder.AddSerilog.
Here's what works for me.
using Serilog;
(...)
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
(...)
.CreateLogger();
(...)
return new HostBuilder()
.ConfigureHostConfiguration(...)
.ConfigureServices(...)
.UseSerilog();
I'd like to use Serilog for my project, but I can't quite get it to work properly.
Right now, this is what I've got, just for verifying and testing purposes:
public MainLogger([NotNull] ILogPathProvider logPathProvider)
{
m_logger = Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
m_logger.Warning("blabla");
}
As you can see, there is not a lot going on besides just opening a log and trying to write a warning.
However, this warning does not appear.
Is there anything I forgot to configure / call?
Assuming you installed the correct NuGet Packages (Serilog and Serilog.Sinks.Console), then your code sample should print a Warning message in the console without requiring any changes.
You can confirm this by creating a simple Console application, installing the packages above, and running the same code.
The problem is elsewhere in your application and/or environment... It has nothing to do with Serilog.
Most likely, your method MainLogger is not being called at all, or perhaps your Console output is being redirected to somewhere else.
I am using SEQ, file and JSON as a Serilog sinks
Log.Logger = new LoggerConfiguration()
.Enrich.With(new ThreadIdEnricher())
//.Enrich.FromLogContext()
.WriteTo.RollingFile(#"C:\QRT\Logs\QRT-LOG.txt", LogEventLevel.Information)
.WriteTo.Seq("http://localhost:5341")
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)
.WriteTo.File(new CompactJsonFormatter(), "C:/QRT/Logs/log.clef")
.CreateLogger();
SEQ is for me because it looks like it would be really useful.
JSON I may do away with... I was attempting to write a file that I could import into Access. The point is that I need my non-developer friend to be able to see the logs and Access is a tool I believe he can use to easily filter on items such as Customer ID etc. I have not been able to find much documentation on the Serilog sinks other than their names. Can someone either suggest a mechanism to sink to something that can be imported to Access or another sink that a user-friendly tool can ready?
I am currently using NLog and GamutLogViewer which is awesome because it can color entries based on regular expressions!
Any suggestions would be most welcome. The idea is my friend is not looking at the logs to debug. He will be looking at the "Information" contained in the logs.
This is using C# on a console app in Windows.
Thanks
-Ed
Serilog has a sink called Serilog.Sinks.NLog which adapts Serilog to write events through your existing NLog infrastructure, which means you can effectively use Serilog throughout your app, but output log files in the NLog format, which would be readable by the GamutLogViewer (or YALV! as an alternative).
Another approach I can think of is to use the sink Serilog.Sinks.MSSqlServer where you write your logs to a SQL Server table (could even be a SQL Server Express instance on the user's machine, if you don't want/have a shared SQL Server) and then use Microsoft Access to query these logs via linked tables in Access.
Ultimately, you could develop your own sink that writes directly to a .csv file or even directly to an Access .accdb file, for example. Developing Sinks for Serilog is super easy and there are tons of examples you can use as a base for your custom sink.
Can any one let me know how to implement logging with Enterprise Library 6.0 in C#. I want to do logging in Database, if it is available otherwise log the exceptions , information, messages into LOG file.
Can anyone tell me How to implement logging into Db, otherwise log in file dynamically.
I will have both logging DB and file config changes in App.config/Web.config.
So please help me on this how to implement logging dynamically based on runtime value:
If Db is available and accessible, then log, otherwise if DB is not accessible, then log to Log-file or event-viewer.
The new version 6 makes comprehensive use of the factory pattern, hence you need to set the logger up differently in version 6:
Try the following:
IConfigurationSource configsrc = ConfigurationSourceFactory.Create();
LogWriterFactory logWriterFactory = new LogWriterFactory(configsrc);
Logger.SetLogWriter(logWriterFactory.Create());
Logger.Write("logtest", "General");
Your description of your database logging requirements isn't quite clear, but I think these Code examples and links should be what you are looking for.
I've been trying to work with ETW in .net 4.5.
I have a WCF Service and Console App, and I want which uses EventSource to write messages, however, I'm struggling to understand how to create my own ETW (EventSource and EventListener) for log to a file (rolling file).
Any suggestions?
In addition to magicandre1981's answer, you should add: -
TraceEventSession _session = new TraceEventSession(
"yourSessionName", #"C:\yourLogFile.etl")
{
CircularBufferMB = 100 //100mb rolling log file
};
_session.EnableProvider(TraceEventProviders.GetEventSourceGuidFromName(
"Samples-EventSourceDemos-EventLog"), TraceEventLevel.Always);
This can be in the same application as you are logging from (in process), or in a completely separate application (out of process).
Install the Nuget Package of Microsoft EventSource Library
Install-Package Microsoft.Diagnostics.Tracing.EventSource -Pre
and define the Events in a class which is derived from EventSource.
Now use the Semantic Logging Application Block from Enterprise Library to consume Events.
Here is a video how to use it:
Introducing Semantic Logging
http://channel9.msdn.com/posts/Introducing-Semantic-Logging