简体   繁体   中英

Enterprise Library Logging isn't log on SQL

I'm using EntLib 6 in order to log one webapp. Because I'm using n-layers, I wanted to put the logging in one library, accessible from all layers.

I'm trying to run the logging but nothing happends, all the code is running, no exception but nothing appears in DB.

So this is what I've done:

I've created DB with script provided in EntLib6 into the DB that is beneath DB_BELVAL Connexion string, I put this c# test code in the portable class that will handle logging:

 public static void LogToDatabase()
        {
            try
            {
                //Bootstrapping logging
                DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
                IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
                LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
                Logger.SetLogWriter(logWriterFactory.Create());

                if (Logger.IsLoggingEnabled())
                {

                    LogEntry log = GetLogEntry();
                    log.Categories.Add("General");  // name of Categorie in EntLib Config editor
                    log.Priority = 5;
                    log.Severity = System.Diagnostics.TraceEventType.Information;
                    log.Message = "Hello dude, from AMLogger";
                    Logger.Write(log);

                }

            }
            catch (Exception ex)
            {
            }
        }

        private static LogEntry GetLogEntry()
        {
            LogEntry log = new LogEntry();
            log.TimeStamp = DateTime.Now;
            log.Title = "TANOLIS";
            log.Priority = 5;                       // default priority
            log.Severity = System.Diagnostics.TraceEventType.Verbose;  // default severity
            log.MachineName = "MachineName";//HttpContext.Current.Server.MachineName;
            log.ProcessId = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
            return log;
        }

And from the UnitTest, I call the LogToDatabase() method of the portable library. I configured the config file of the Unit test as that:

EntLib编辑器

or the xml:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>
  <loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
    <listeners>
      <add name="Database Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        databaseInstanceName="DB_Belval" writeLogStoredProcName="WriteLog"
        addCategoryStoredProcName="General" formatter="Text Formatter" />
    </listeners>
    <formatters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
        name="Text Formatter" />
    </formatters>
    <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="Database Trace Listener" />
        </listeners>
      </add>
    </categorySources>
    <specialSources>
      <allEvents switchValue="All" name="All Events">
        <listeners>
          <add name="Database Trace Listener" />
        </listeners>
      </allEvents>
      <notProcessed switchValue="All" name="Unprocessed Category">
        <listeners>
          <add name="Database Trace Listener" />
        </listeners>
      </notProcessed>
      <errors switchValue="All" name="Logging Errors &amp; Warnings">
        <listeners>
          <add name="Database Trace Listener" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>
  <dataConfiguration defaultDatabase="DB_Belval" />
  <connectionStrings>
    <add name="DB_Belval" connectionString="Data Source=serverIP;Initial Catalog=APP_Dev;Persist Security Info=True;User=login;Password=password"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Indeed, nothing happends, but I breakpointed the UnitTest and all looks right, no exception.

Thanks to help me

**EDIT 1 : **: logWriterFactory looks like it has loaded the XML: 视觉工作室

EDIT 2 : I've edited the stored procedure [dbo].[WriteLog] in order to make a kind of flag (one INSERT INTO [dbo].[TestLog]) to know if stored proc is called and it looks that app doesn't call the stored proc:

ALTER PROCEDURE [dbo].[WriteLog]
(
    @EventID int, 
    @Priority int, 
    @Severity nvarchar(32), 
    @Title nvarchar(256), 
    @Timestamp datetime,
    @MachineName nvarchar(32), 
    @AppDomainName nvarchar(512),
    @ProcessID nvarchar(256),
    @ProcessName nvarchar(512),
    @ThreadName nvarchar(512),
    @Win32ThreadId nvarchar(128),
    @Message nvarchar(1500),
    @FormattedMessage ntext,
    @LogId int OUTPUT
)
AS 


INSERT INTO [dbo].[TestLog]
           ([text]) VALUES ('Storeproc1')




    INSERT INTO [dbo].[Log] (
        EventID,
        Priority,
        Severity,
        Title,
        [Timestamp],
        MachineName,
        AppDomainName,
        ProcessID,
        ProcessName,
        ThreadName,
        Win32ThreadId,
        Message,
        FormattedMessage
    )
    VALUES (
        @EventID, 
        @Priority, 
        @Severity, 
        @Title, 
        @Timestamp,
        @MachineName, 
        @AppDomainName,
        @ProcessID,
        @ProcessName,
        @ThreadName,
        @Win32ThreadId,
        @Message,
        @FormattedMessage)

    SET @LogID = @@IDENTITY
    RETURN @LogID

And there is no new lines in [dbo].[TestLog] when I launch the UnitTest so the issue seems to be in C#

Looks like you already spent some time tearing your hair out. My 2 cents would be to gather as much debug info as you can. I don't have any prior experience with EL.

Here are my tips;

  1. I would advise you to monitor ALL transacitons/requests on the target database. To do so, just open the SQL Profiler from SSMS and run it without any filter other than the Database Name (or on your entire server). By the way, is it a local or remote DB? If remote, filter on your username to avoid nose from other developers/users.

  2. Check if there is no missing DLL or loading exceptions thrown by EL. Use Fusion Log. I can provide you with info about how to use it if needed.

Run the Fuslogvw.exe utility from MS SDK tools (C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v10.0A\\bin\\NETFX 4.6 Tools), take the highest version. Run as admin to edit the settings of Fusion (set Custom Log Path to "C:\\Fuslog") Create the directory "C:\\Fuslog" (must exist in order to enable the logging). DISABLE fusion once you have finished.

  1. From the Exceptions window of Visual Studio, disable "Enable Just My Code", enable "break when exception cross appdomain or..." (the last one is not really relevant in your case, we never know).

You can also enable ".NET Framework Source Stepping" but it will need some time to download the symbols.

If you go for this one, make sure the symbols are loaded corretcly for EL by displaying the Symbols Window.

More over here: http://blogs.msdn.com/b/saraford/archive/2008/08/26/did-you-know-how-to-load-symbols-from-the-modules-window-299.aspx

Keep us posted!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM