Temporarily Disable logging for log4net - c#

How can I temporarily disable logging of log4net based on the result of my function?
example:
if (MyCondition)
{
//Stop logging
}
else
{
//go on, log me...
}
i tried using these codes:
LogManager.GetRepository().Threshold = LogManager.GetRepository().LevelMap["OFF"];
LogManager.GetRepository().Threshold = LogManager.GetRepository().LevelMap["ALL"];
to try to disable log4net logging, but the results are the same. log4net is still logging.
Can this be done?

It might be easier to set the logging to "OFF" for all loggers at runtime, then switch them back on afterwards.
Some more info can be found here: http://geekswithblogs.net/rakker/archive/2007/08/22/114900.aspx

Related

Why the LogLevel rule is not set for my NLog?

I want to set the log level programmatically.
But when I look up my logs, all logs are written (from Trace to Error).
I code it like the example on stackoverflow.
foreach (var rule in NLog.LogManager.Configuration.LoggingRules)
{
//rule.EnableLoggingForLevel(nlogLevel);
rule.EnableLoggingForLevels(NLog.LogLevel.Warn, NLog.LogLevel.Fatal);
}
NLog.LogManager.ReconfigExistingLoggers();
Logger.LogTrace("LogLevel Trace");
Logger.LogDebug("LogLevel Debug");
Logger.LogInformation("LogLevel Info");
Logger.LogWarning("LogLevel Warn");
Logger.LogError("LogLevel Error");
I tried
rule.EnableLoggingForLevel(nlogLevel);
and
rule.EnableLoggingForLevels(NLog.LogLevel.Warn, NLog.LogLevel.Fatal);
Screen shot of the log's:
Why I can't change the log level?
This also happened to me and I was able to solve it by running LogManager.ReconfigExistingLoggers(); after changing log levels.
This will work for your case:
rule.SetLoggingLevels(NLog.LogLevel.Warn, NLog.LogLevel.Fatal);
From documentation:
Enables logging the levels between (included) minLevel and maxLevel. All the other levels will be disabled.
https://nlog-project.org/documentation/v4.5.0/html/M_NLog_Config_LoggingRule_SetLoggingLevels.htm
This is correct, enabling a loglevel doesn't mean disabling another.
Otherwise this will be an issue:
rule.EnableLoggingForLevel(LogLevel.Warn);
rule.EnableLoggingForLevel(LogLevel.Error); // luckily this won't disable Warn
What you could do:
Disable all loglevels first, and then enable the ones you need
rule.DisableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal); // disable all
rule.EnableLoggingForLevels(NLog.LogLevel.Warn, NLog.LogLevel.Fatal); // enable needed
For this case - a minimum for all rules - there is also an easier way:
LogManager.GlobalThreshold = LogLevel.Info; // For all rules, minimum is Info
Please note that it's unclear why all the levels are enabled by default in your code. That's configured in the nlog.config or code, as that is not a default from NLog.

Standard way to keep debug lines in the program

I would like to add some debug lines to my program. Once after executing statements it will record the current status to a file.
I have done that in following way.
public int? DoWork(int x, int y)
{
Log.Write("Received inputs. X an Y values are:"+x+","+y);
bool result = ChekData(x);
if (!result)
{
Log.Write("First input is not valid");
return null;
}
result = ChekData(y);
if (!result)
{
Log.Write("Second input is not valid");
return null;
}
Log.Write("Valid input found");
....
....
}
I feel this is not the standard wa to do this. Keeping text like this in the code. After searching I found using Resource file I can save these messages like name value pair.
But I have no idea about the standard of that. Please advise me.
Basicaly for the loging I am using Log4Net
This is pretty normal way of doing logging.
Using resource files for logging generally does not make sense because:
it moves descriptive message away from the place it most useful - inline code
logs most commonly used by original developers, so getting logs in Japanese (if log resource strings are properly localized) is rarely useful for English speaking developers and vise versa.
avoiding localization of some strings (one that are used for logging) may be inconvenient, localizing them is not free...
If it is only for debug purpose i would do the following:
Set appropriate debuglevels. The debug version should then be build using a level to show all messages. The release build normally don't need debug outputs. Therefore disable the message level for release output.
For distinction if you are in release build or debug build you can use the following 2 things:
#if DEBUG
// enable all tracing
#endif
or if you also want that your realease build brings messages if a Debugger is Attached
if(System.Diagnostics.Debugger.IsAttached)
{
// Someone has attached a debugger, so give more output
}
You can also wrap the logcalls if you want with a method which justs checks for debug/attached debugger..

nhibernate log to stdout

I am using Nhibernate 3.3 and I have set up the configuration so that it should log SQL, etc. In the past (NH 2.2+) I have set stdout to a StreamWriter like so:
string nhLoggerPath = "...path...";
Logger = new StreamWriter(nhLogPath, false, Encoding.UTF8);
Console.SetOut(Logger);
And everything was working just fine. Now with version 3.3, I get everything in my log file as before, EXCEPT for the sql that Nhibernate is supposed to be logging. What has changed, or what do I need to do to get everything working again?
p.s. I am not using log4net (obviously) and I don't care to either.
Here is how I am setting up the logging....
...
db.ConnectionString = #"myConnectionString";
db.LogSqlInConsole = true;
db.LogFormattedSql = true;
...
how do you setup logging sql? NH 2.x used log4net exclusivly, NH3.x has an internal logger implementation which defaults to log4net if present or nologging when not present. You probably did not configure it to log to console.

Checking Event Log writing Permissions without writing an entry

I need to check if a user has write permissions for the event log. My solution right now is to write a test message in the log and delete it afterwards (so that the log does not get messed up, as the check for permissions is called often (every 3-5 Mins.) by some 'Healthcheck'-service:
const string log = "MyApplicationLog";
const string source = "PermissionCheck";
EventLog evLog;
try
{
if (!EventLog.SourceExists(source))
{
EventLog.CreateEventSource(source, log);
}
evLog = new EventLog();
evLog.Source = source;
evLog.WriteEntry("PermissionCheck Test Message");
return true;
}
finally
{
//remove the check messages:
if (EventLog.Exists(log))
{
EventLog.Delete(log);
}
}
Is there any possibility to check the permissions without actually writing a log entry?
Thank you in advance,
ElKunzo
Yes, AFAIK, using CAS. Decorate the required member/s with the EventLogPermission attribute, from there you can control whether you must have access, only desired and so forth.
This may well entail a little further adventure in CAS itself, however, if you're unfamiliar.
MSDN Link.

How to write to a custom event log?

I'm trying to get my .Net Windows Service to right to a custom event log. I'm using EventLogInstaller to create the event log and source when the application is installed. I read here that it takes a while for Windows to register the source so they reccomend you restart the application before trying to write to the log.
As this is a Windows Service I didn't want to have to force a computer restart or get the user to manually start the service up, so I use this code to wait for the log to exist and then start the service automatically.
while (!(EventLog.Exists("ManageIT") || EventLog.SourceExists("ManageIT Client Service")))
{
Thread.Sleep(1000);
}
System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("ManageIT.Client.Service");
controller.Start();
My problem is that events from the service are still written to the Application Log and although I can see my custom log in the Registry Editor it does not show up in the Windows 7 Event Viewer.
Any help will be much appreciated.
By default when a service is installed, the source gets associated with the Application Log.
If we change this association at a later point, the system needs a restart.
We can however prevent the association of the service with the application log, by setting autolog property to false in the service class (class which inherits from servicebase) constructor.
http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.autolog.aspx
Try this snippet:
edit - caveat: if the user running the code does not have administrator rights, this will throw an exception. Since this is the case (and if the user will not have these rights) best practices should be to assume the log exists, and simply write to it. see: The source was not found, but some or all event logs could not be searched
if (!EventLog.SourceExists("MyApplicationEventLog"))
{
EventSourceCreationData eventSourceData = new EventSourceCreationData("MyApplicationEventLog", "MyApplicationEventLog");
EventLog.CreateEventSource(eventSourceData);
}
using (EventLog myLogger = new EventLog("MyApplicationEventLog", ".", "MyApplicationEventLog"))
{
myLogger.WriteEntry("Error message", EventLogEntryType.Error);
myLogger.WriteEntry("Info message", EventLogEntryType.Information);
}
It sounds like you are writing to the event log like this:
EventLog.WriteEntry("Source", "Message");
This will write to the application log.
If you use the code in simons post with the creation of myLogger, you can specify the name of the Log.
I did something like this:
var logName = EventLog.LogNameFromSourceName("MyApp", Environment.MachineName);
//delete the source if it associated with the wrong Log
if (!string.IsNullOrEmpty(logName) & logName != "MyLog")
{
EventLog.DeleteEventSource("MyApp", Environment.MachineName);
}
if (!EventLog.SourceExists("MyApp"))
{
EventLog.CreateEventSource("MyApp", "MyLog");
}

Categories

Resources