Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7033927
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T01:07:27+00:00 2026-05-28T01:07:27+00:00

I’m using EF 5 and am trying to use the ShouldLog method to determine

  • 0

I’m using EF 5 and am trying to use the ShouldLog method to determine whether a LogEntry will be logged prior to actually logging it. My issue is that ShouldLog always returns true, even if I have a filter in place to exclude certain levels. The filter works and the entries are not logged, but ShouldLog does not appear to work.

I’m configuring my logger like so:

internal static void ConfigureLogging(SourceLevels logLevel)
{
    var builder = new ConfigurationSourceBuilder();

    builder.ConfigureLogging()
        .LogToCategoryNamed("General")
        .WithOptions.SetAsDefaultCategory()
        .SendTo.FlatFile("Main log file")
        .FormatWith(
            new FormatterBuilder()
                .TextFormatterNamed("Text Formatter")
                .UsingTemplate("{timestamp(local:MM/dd/yyyy HH:mm:ss.fff)} [{severity}] {message}"))
        .Filter(logLevel) //Setting the source level filter
        .ToFile("log.txt");

    var configSource = new DictionaryConfigurationSource();
    builder.UpdateConfigurationWithReplace(configSource);
    EnterpriseLibraryContainer.Current
        = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
}

And testing it like this:

ConfigureLogging(SourceLevels.Warning); //Do not allow Information level

var logEntry = new LogEntry { Message = "test", Severity = TraceEventType.Information };
var shouldLog = Logger.Writer.ShouldLog(logEntry);
Logger.Writer.Write(logEntry);

After I run this code the shouldLog variable is true, but no log entry is written. If I pass SourceLevels.Information to the ConfigureLogging method instead I do get an entry written to my log. Am I doing something wrong?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T01:07:27+00:00Added an answer on May 28, 2026 at 1:07 am

    I don’t think you are doing anything wrong. However, I’ll admit the behavior is a bit odd.

    As mentioned here the ShouldLog method queries all of the configured Filters against the LogEntry. The reason why ShouldLog returns true is that you haven’t defined any filters so everything passes.

    “But wait!”, you say. “I’ve set the source level Filter in the fluent configuration!”

    That’s true — in a sense. But despite it’s name the Filter method doesn’t create an actual filter (perhaps it should, though)! It basically just sets a SourceLevels value which only gets checked when Write is called. If you use the configuration file instead of the fluent configuration then in the config file Filter is actual named switchValue so it’s not quite as confusing.

    So ShouldLog returns true because there are no filters but Write does not actually write because of the check against SourceLevels. This is pretty counter-intuitive. It would be nice if in version 6 the check could be included in ShouldLog? It defeats the purpose of ShouldLog if it returns true which causes the user to construct a bunch of expensive objects but in the end the message is never logged because of the SourceLevels check.

    I checked and it looks like this behavior has been around since at least version 4.

    What to do about this behavior? The easiest way is to add a custom filter to perform the SourceLevels check:

    public class SourceLevelFilter : LogFilter
    {
        private SourceLevels level;
    
        public SourceLevelFilter(NameValueCollection nvc)
            : base("SourceLevelFilter")
        {
            if (!Enum.TryParse<SourceLevels>(nvc["Level"], out level))
            {
                throw new ArgumentOutOfRangeException(
                    "Value " + nvc["Level"] + " is not a valid SourceLevels value");
            }
        }
    
        public override bool Filter(LogEntry log)
        {
            if (log == null) throw new ArgumentNullException("log");
            return ShouldLog(log.Severity);
        }
    
        public bool ShouldLog(TraceEventType eventType)
        {
            return ((((TraceEventType)level) & eventType) != (TraceEventType)0);
        }
    
        public SourceLevels SourceLevels
        {
            get { return level; }
        }
    }
    
    // ...
    
    SourceLevels logLevel = SourceLevels.Warning;
    
    var builder = new ConfigurationSourceBuilder();
    
    builder.ConfigureLogging()
        .WithOptions
        .FilterCustom<SourceLevelFilter>("SourceLevelFilter", 
            new NameValueCollection() { { "Level", logLevel.ToString() } } )
        .LogToCategoryNamed("General")
        .WithOptions.SetAsDefaultCategory()
        .SendTo.FlatFile("Main log file")
        .FormatWith(
            new FormatterBuilder()
                .TextFormatterNamed("Text Formatter")
                .UsingTemplate("{timestamp(local:MM/dd/yyyy HH:mm:ss.fff)} [{severity}] {message}"))
        .Filter(logLevel) //Setting the source level filter
        .ToFile("log.txt");
    

    Now ShouldLog will incorporate the SourceLevels value in its check and will return false for the LogEntry with the Information severity when the SourceLevels is set to Warning.

    UPDATE

    One issue you might have with filters is that they are global so you’d probably have to beef up the filter above to store the SourceLevels along with the Category.

    If you just wanted to check if Warning was enabled you could check the specific filter:

    public bool IsWarningEnabled
    {
        get
        {
            return writer.GetFilter<SourceLevelFilter>().ShouldLog(TraceEventType.Warning);
        }
    }
    

    Another approach would be to manage the SourceLevels yourself without a filter. Since you are writing a general purpose log wrapper then I assume that the SourceLevels will be set through your wrapper. You also talk about exposing your own methods such as IsDebugEnabled. If so, then you can maintain that knowledge internal to your wrapper and provide that check on demand. If you are returning EntLib LogWriters to callers then that might work since the user would want to call ShouldLog on the LogWriter. Although, you could also create extension methods (such as IsWarningEnabled() ) on LogWriter.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I want use html5's new tag to play a wav file (currently only supported
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We are using XSLT to translate a RIXML file to XML. Our RIXML contains

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.