Owin produces a lot of logging noise in the trace - c#

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)

Related

Serilog not logging anything

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.

Owin WebApp Dispose does not release URL Registration

I'm using SignalR in a .Net Windows service (using Microsoft.Owin v4.0.1.0). Due to the requirements of the application, I need to be able to stop and later restart the SignalRHub. The code I doing this with is
HubWebApp = WebApp.Start(HubURL)
Then later:
HubWebApp.Dispose()
Then later still:
HubWebApp = WebApp.Start(HubURL)
The problem is that when I start the WebApp for the 2nd time after earlier disposing of it to stop the SignaRHub, I'm getting the error:
"Failed to listen on prefix 'http://172.16.4.55:8080/' because it
conflicts with an existing registration on the machine".
So it looks like it's not releasing the URL registration when I dispose the WebApp, and refusing a new listener on this same URL when I restart it.
I tried messing around with netsh http, but delete doesn't work and show doesn't show the existing registration.
How can I release the URL registration when I dispose the WebApp?
Never found solution to unregister the URL. What I wound up doing is coding the service to exit with an error if restarting the hub throws an exception (Environment.Exit(1)). Then configure the service in Service Manager to automatically restart if it exits with an error.
This is a real Wear A Paper Bag Over Your Head kludge, but it's the best answer I've got for now.

Serilog SelfLog to File Error

I need to enable self log of seri logger to text file. My configuration are follows;
__serilogLogger = new LoggerConfiguration()
.Enrich.WithProperty("ApplicationIPv4", _ipv4)
.Enrich.WithProperty("ApplicationIPv6", _ipv6)
.WriteTo.MSSqlServer(connectionString, tableName /*, columnOptions: columnOptions*/)
.WriteTo
.Seq(ConfigurationManager.AppSettings["SerilogServer"])
.CreateLogger();
var file = File.CreateText("Self.log");
Serilog.Debugging.SelfLog.Enable(TextWriter.Synchronized(file));
But is hows File access error when run the application. Please find the error details below;
Additional information: The process cannot access the file 'C:\Program
Files (x86)\IIS Express\Self.log' because it is being used by another
process.
Can anyone help me on this
try
Serilog.Debugging.SelfLog.Enable(msg => File.AppendAllText (serilogSelfLogFilePath, msg));
for a non-locking way to write to a file. serilogSelfLogFilePath is a valid path string to the file you want to use.
Don't forget Log.CloseAndFlush(); when you're closing your other logs per https://github.com/serilog/serilog/issues/864 or it won't get written anyway
Note, if you are using an async Sink then you will eventually get an exception when different threads contend to write to that file if it gets busy.
You must have another instance of this application running when it comes to this line. Or maybe this code is somehow being invoked twice? Check taskmanager and kill anything that maybe using it. If this is a web app try recycling the app pool.
I was facing a problem manifesting this same The process cannot access the file 'X' because it is being used by another process. error message. In my case it appeared in the server's event log every time the application pool recycled in IIS 8.5, even though Maximum worker processes was set to 1. Maybe worth saying: the code enabling self log executes in a static constructor.
No luck did I have after properly closing the TextWriter, not even when adding generous Thread.Sleep before File.CreateText in hope of waiting for that "another process" to finish.
The solution was to set Disable Overlapped Recycle to true in Advanced Settings for the application pool.

Using internal log and manage exceptions

I've two problem using Nlog internal logging.
Firstly while starting I execute the following code:
LogManager.Configuration = new
NLog.Config.XmlLoggingConfiguration("NLog.debug.config", true);
LogManager.ReconfigExistingLoggers();
InternalLogger.LogToConsole = true;
InternalLogger.LogToConsoleError = true;
InternalLogger.LogLevel = LogLevel.Trace;
LogManager.ThrowExceptions = true;
InternalLogger.LogFile = Path.Combine(ConfigurationManager.AppPath, "Nlog.log");
My first problem is the logToconsole do not display in my Visual output. Is that normal ?
My second issue is when I try to log on C:\log.txt (to test internal log)
This should crash because Nlog cannot create files at the root of C:.
Unfortunaly It do not crash (and do not create the file) (it works with C:\test\log.txt for example).
Here my internal Nlog.log content:
2015-04-23 18:44:09.8593 Debug TestManager.Info Rejecting message
because of a filter. 2015-04-23 18:44:09.8593 Debug TestManager.Info
Rejecting message because of a filter. 2015-04-23 18:44:09.8593 Debug
TestManager.Info Rejecting message because of a filter. 2015-04-23
18:44:09.8593 Debug TestManager.Info Rejecting message because of a
filter. 2015-04-23 18:44:09.8593 Trace Opening C:test.log with
concurrentWrite=False
Rejected is normal (I've several targets)
So Why haven't I exception and no trace ?
Thanks a lot for the incoming help
NLog probably uses the conventional Console.WriteLine(…) method to send messages to console. It will not work in WinForms application because Console.WriteLine(…) does nothing in WinForms application by default. It only works, however, when you are debugging from Visual Studio since that provides a console window for Output
Try to call Win32 API function AllocConsole at the beginning of your application. It should create a console for your WinForms application and enable Console.WriteLine(…) function. Here you can find an example of the code that shows how to call AllocConsole. "See link for setting this up".
Also quoting Nlog github page on internal logging
There are 3 environment variables which control internal logging. You
can set those variables before running your program to enable internal
logging:
NLOG_INTERNAL_LOG_TO_CONSOLE - if this variable is found in the
environment, will outputs internal diagnostic information to the
console
For your second question, looking at your logs I believe you did not provide the path in correct format by escaping the backslash character
It should be like
fileName="C:\\logssamplefile.txt"
Please note that this worked for me

OWIN interferes with log4net

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)

Categories

Resources