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.
Related
I'm having some trouble with Application Insights when running a C# v3 Function App. Everything is setup within Azure to use Application insights, as per the instructions. Within the host.json file, I've included the following settings:
"logging": {
"LogLevel": {
"Default": "Information"
},
"applicationInsights": {
"samplingExcludedTypes": "Request",
"samplingSettings": {
"isEnabled": true
}
}
},
I am using Dependency Injection, so have a startup class within the app, and then inject ILogger class wherever required:
using Microsoft.Extensions.Logging;
...
builder.Services.AddLogging();
There are a few occasions within code where I'm catching an exception, handling it, and want to log it rather than throw an exception. E.g. looking for a blob container image that may or may not exist - I can still return a valid response rather than throwing the whole thing because of a single, trivial issue.
However, Application Insights does not seem to be logging the exception within the trace, even though it has been passed to the logger:
catch (ArgumentException e)
{
var msg = $"Error encountered blah blah blah";
logger.LogWarning(e, msg);
return Result.Failure<string>(msg);
}
I can see within Application Insights the warning being logged, along with the message, but the stack trace is always missing from the message/custom dimensions within the trace. The same happens if I use LogError.
Custo:
traces
| where cloud_RoleName == "my-app" and severityLevel == 2
I've looked through a fair amount of documentation and questions on here, but struggling to find an answer that works, or that explains well what is going on. It seems very much with Azure Functions + App Insights that either "it just magically works if you turn it on", or the answers are for ASP.NET core, or just plain out of date.
Is the problem that only exceptions thrown by the app will show up in the Exceptions area of App Insights with a stack trace? (if so, can you log errors here without throwing an exception?)
Am I missing a key bit of config in host.json or startup? A library? (I've already tried adding Microsoft.Azure.WebJobs.Logging.ApplicationInsights)
I'm also looking at changing over to use Serilog + an App Insights sink if necessary - but don't especially want to do this when it seems like it should "just work out of the box".
Can anyone help?
Thanks to #PeterBons for his help, in order to get your logged exceptions to appear in the Exceptions table in App Insights you need to make sure that:
If you're using sampling, you add "Exception" to the "samplingExcludedTypes" in your host.json to make sure they all get logged
You need to reference the "Microsoft.Azure.WebJobs.Logging.ApplicationInsights" nuget package in your project (I left everything else the same and removed this - boom, no logging to exceptions)
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/
I've got a small console application running TopShelf and using Serilog as the logging facility where I'd like to run OWIN inside. However as soon as I start the app builder, every log message gets duplicated via the trace listener and thus, printed out twice to the console.
// serilog sink configuration
new LoggerConfiguration()
.WriteTo.Trace()
...
.CreateLogger();
// topshelf
HostLogger.UseLogger(new SerilogLogWriterFactory.SerilogHostLoggerConfigurator());
I already found this answer here and included the following before I start the web host:
webHostOptions.Settings.Add(typeof (ITraceOutputFactory).FullName,
typeof (WebAppBuilder.NullTraceOutputFactory).AssemblyQualifiedName);
Trace.Listeners.Remove("HostingTraceListener");
The funny thing is: When I first started the application after inserting those lines, it worked (e.g. double messages were gone.). However after I cleaned my \bin directory, they started to appear again. What do?
Please check out this highly professional drawing I just made which should further explain the issue:
(zoom)
In my application, I've got the following logging strategy/appenders:
DebugAppender: If the root level is DEBUG, write every message that matches DEBUG to the default trace listener output
ConsoleAppender: If the application mode (global context property) is 'console', write every message above WARN to the console ouput
EventLogAppender: If the application mode (global context property) is 'service', write every message above ERRROR to the console output
RollingFileAppender: Write every message above INFO to a rolling flat file
This works very well throughout the whole application, until the very first line I'm starting the OWIN web host using the IAppBuilder interface. As soon as I invoke WebApp.Start, I noticed the following behavior:
Debug messages (ILogger.Debug) are getting written to the console output
Debug messages (ILogger.Debug) are getting written twice to the VS debug output
Upon further investigation, I figured out that OWIN silently attached an instance of System.Diagnostics.DefaultTraceListener and System.Diagnostics.TextWriterTraceListener to the default trace/debug ouput, which may be the root of the problem. However, declaring the DefaultTraceListener in app.config explicitly didn't help.
Is there any way I can configure OWIN to be less... sneaky?
You can remove the listener in startup code, eg:
Trace.Listeners.Remove("HostingTraceListener");
(Name from source code)
I am developing c# application, which is running as a windows service.
What ever transactions we are doing in the application i am writing it into log file.
A log directory is added in app.config file as below.
<add key ="LogDir" value="log" />
<add key ="LogLevel" value="2" />
And in the c# code the above one is accessing as below.
int logLevel = Convert.ToInt32(ConfigurationManager.AppSettings["logLevel"]);
if (logLevel > 0)
{
logger = new Logger();
logger.TraceLevel = logLevel - 1;
logger.logDir = ConfigurationManager.AppSettings["logDir"];
logger.logFileBaseName = "touchserver";
}
And then when any process is happening i am writing the data to the log as below.
TouchServer.Log(Logger.MessageType.Trace, 1, "Item successfully deleted");
And when i run my application in debug mode (i mean as console application) the log file will be created in the application's debug folder and the data will write into the log file.
But my problem is that when i install my application as service the log file is not getting created in the debug folder, and i am unable to see the actions performed , in case if anything went wrong.
Please help me to find a solution in this.
And i am installing service using Installutil command.
Thanks in advance
sangita
While you could get into why this is not working and fix the solution, overall there is no need to implement a logging component.
There are excellent free libraries available that do this very well. log4net is very popular. It is easy to use, feature rich and efficient. Take a look at it.
But my problem is that when i install my application as service the log file is not getting created in the debug folder, and i am unable to see the actions performed , in case if anything went wrong.
Check out what are the result of the IO operations by using Process Monitor. I suspect you'll find the identity being used to run the service process does not have write permissions where it is trying to write the log file.
But the better option is to use an existing logging library as Hemal suggests.