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.
Related
I got a task which is need to check whether a specific class with Summary when it is checked-in on Team Foundation System.
I have found a way which is turn on the code analysis in the process of check-in, the problem is there is no Summary checking item in rules.
Is there any way to check each class whether with Summary during the check-in?
Is it possible to customize BuildprocessTemplate to make it?
can this checkin policy evaluate make it?
public override PolicyFailure[] Evaluate()
{
List<PolicyFailure> failures = new List<PolicyFailure>();
foreach(PendingChange pc in PendingCheckin.PendingChanges.CheckedPendingChanges)
{
if(pc.LocalItem == null)
{
continue;
}
/* Open the file */
using(FileStream fs = new FileStream(pc.FileName,FileMode.Open,FileAccess.Read))
{
StreamReader fs1 = new StreamReader(fs);
string eachline= fs1.ReadLine();
int PublicCount=0;
int SummaryCount = 0;
while(eachline !="")
{
if (eachline.IndexOf("/// <summary>")!=-1)
{
SummaryCount++;
}
if (eachline.IndexOf("public")!=-1)
{
PublicCount++;
}
}
if(PublicCount != SummaryCount)
{
failures.Add(new PolicyFailure("Class Summary missing"));
}
fs.Close();
}
}
return failures.ToArray();
}
I'd recommend against a custom TFS check in policy. They get evaluated on the client meaning a) they interfere with developer workflow b) they can get overridden on the client (and it can be difficult to get notifications when developers override the policy), and most importantly c) you need to manage getting the assembly with your custom policy on it onto your developer machines and keeping it up-to-date.
The best thing to do, I think, is to integrate StyleCop with MSBuild so that you get build warnings or errors if StyleCop detects issues. There's a handy nuget package to get you started. This gives you a lot of flexibility to enforce code style rules. You can use this alongside the last-build-successful policy, or better use Gated Checkins so that the evaluation happens on the server.
Bear in mind the following:-
If you want to fail the build because of StyleCop violations, you'll need to set <StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings> in your project file.
From personal experience, I'd recommend only setting StyleCopTreatErrorsAsWarnings false on your release configuration(s). If your developers have to add xml comments before they can, say, check if something compiles, then you're going to have trouble!
You'll need to spend a little time setting up which StyleCop rules you want to enforce for your project. Make sure they get source-controlled along with the .sln - you don't want to have to mess around with them on individual developer machines.
Start with a small ruleset that's quite permissive and expand as you go.
Don't waste expensive programmer time manually reformatting code files to match the style guidelines. Get resharper and set it up so that the code cleanup function tidies things up correctly.
As Richard commented a way to check for this is writing a custom policy. A small tutorial can be found here.
Another approach is to write a StyleCop-rule that checks classes if they have a summary. And use this stylecop-checkinpolicy with it.
You can NOT do this using Code Analysis because Code Analysis checks compiled code. During compilation the comments disappear and there is no way to check for them.
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
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..
I've read several articles that tell you how to add text to the output window in visual studio from within an Add-On (specifically, a visual studio 2008 integration package, via the visual studio 2008 SDK 1.1), but no examples of how to read text from the output window. My goal is to parse text from the debug output window while debugging a certain application (TRACE output and possibly stdin/stdout). The IVsOutputWindowPane interface has no methods for reading in text from the output window. The documentation seems to imply that it is possible, but it doesn't provide an example:
http://msdn.microsoft.com/en-us/library/bb166236(VS.80).aspx
Quote: In addition, the OutputWindow and OutputWindowPane objects add some higher-level functionality to make it easier to enumerate the Output window panes and to retrieve text from the panes.
Preferably I'd like to be able to subscribe to an event that fires when a new line of text arrives, similar to a StreamReader's asynchronous reads.
It is possible, it is just a long winding path to get to it:
ServiceProvider -> IVsOutputWindow -> GetPane( debugwindow ) -> IVsUserData -> GetData( wpftextviewhost ) -> IWpfTextViewHost -> IWpfTextView -> TextBuffer -> Changed event.
Presuming you have a VS IServiceProvider from somewhere else (vsix extension/whatever, global service provider), and without any error checking, it looks like this:
IVsOutputWindow outWindow = ServiceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;
Guid debugPaneGuid = VSConstants.GUID_OutWindowDebugPane;
IVsOutputWindowPane pane;
outWindow.GetPane(ref debugPaneGuid, out pane);
// from here up you'll find in lots of other stackoverflow answers,
// the stuff from here down is interesting to this question
IVsUserData userData = (IVsUserData)pane;
object o;
Guid guidViewHost = DefGuidList.guidIWpfTextViewHost;
userData.GetData(ref guidViewHost, out o);
IWpfTextViewHost viewHost = (IWpfTextViewHost)o;
IWpfTextView textView = viewHost.TextView;
textView.TextBuffer.Changed += YourTextChangedHandlerHere;
Your text changed handler will then get called every time the output window gets more data. you won't necessarily get it line by line, but you'll probably more likely than not get big chunks you'll need to deal with on your own.
It is highly likely that some of the above did not even exist in VS in 2010. But it exists now!
The default behavior (when you don’t set the listener explicitly) of VS is to display trace massages in the debugger output window, which you appreciate if you want a simple solution and do no other actions with the massages.
Unfortunately this is not your case. So you have to define a trace listener to send (and store) your trace massages where you then will be able to read them. The trace listener could be a file (for example XML) or you can create a custom listener by deriving a class from the base class TraceListener if you don't want to bother yourself with an additional file.
I don't know that what you ask is possible. But, you can register your add-in as a debugger for your application so that you get the output the trace messages. These are typically routed to OutputDebugString, and can be captured as described in this article: http://www.drdobbs.com/showArticle.jhtml?articleID=184410719. It does not give you the normal output, only debug, but it does not depend on the technology of the debugged application.
The solution on this page selects the text in order to read it. I'm hoping there's a better way.
Automatically stop Visual C++ 2008 build at first compile error?
Private Sub OutputWindowEvents_OnPaneUpdated(ByVal pPane As OutputWindowPane) Handles OutputWindowEvents.PaneUpdated
pPane.TextDocument.Selection.SelectAll()
Dim Context As String = pPane.TextDocument.Selection.Text
pPane.TextDocument.Selection.EndOfDocument()
End Sub
Here's my code:
public void VerifyIfFirstTimeRun()
{
if (System.Configuration.ConfigurationSettings.AppSettings["FirstTimeRunning"] == "true")
{
//Do bla bla bla
//Then do bla bla bla
System.Configuration.ConfigurationSettings.AppSettings["FirstTimeRunning"] = "false";
}
}
Problem is, I'm testing this with the F5 key, it boots up and sure enough using a breakpoint shows that it is indeed going inside the If Condition, but when I "Stop" the application and press F5 again it goes inside the If Condition AGAIN. Is this standard operational procedures?
If so, how can I test if its working?
This is going against the spirit of what the App.config file is used for ... but to answer your question, you need to do System.Configuration.Configuration.Save().
Edit:
App.config is typically used to configure database connections, providers, etc. And is usually set once at installation. It's suggested that user settings go into a separate config file user.config. See this for the explanation.
Edit:
System.Configuration.Configuration class.
Note - now that I read why you're using these settings, may I suggest another way? You should probably just check if the file is there:
if (!File.Exists("thefilepath"))
{
AlertUserOfMissingFile();
ChooseNewFile();
}
It's safer this way anyhow because having a setting set to true doesn't necessarily mean the file is where you think it is.
I'm not sure you should expect this to save; you can, however, have a settings file that has a setting (a bool in this case) in the user's context, which saves (when you ask it to) via Settings.Default.Save().
I don't advice you to use App.settings for this purpose.
Take a look a this article
Settings in C#
In Solution Explorer, expand the Properties node of your project.
In Solution Explorer, double-click the .settings file in which you want to add a new setting. The default name for this file is Settings.settings.
In the Settings designer, set the Name, Type, Scope, and Value for your setting. Each row represents a single setting. Figure 1 shows an example of the Settings designer.
If you want to persist changes to user settings between application sessions, call the Save method, as shown in the following code:
Properties.Settings.Default.Save();