Log4NET将日志写入数据库中

Apache log4net? Config Examples

Overview

This document presents example configurations for the built-in appenders. These configurations are designed to work with thelog4net.Config.DOMConfigurator and the log4net.Repository.Hierarchy.Hierarchy.

These examples are by no means exhaustive configurations for the appenders. For a full list of the parameters that can be specified to each appender and more details on each options see the SDK documentation for the appender.

AdoNetAppender

For full details see the SDK Reference entry: log4net.Appender.AdoNetAppender.

The configuration of the AdoNetAppender depends on the provider selected for the target database. Here are some examples.

MS SQL Server

The following example shows how to configure the AdoNetAppender to log messages to a SQL Server database. The events are written in batches of 100 (BufferSize). The ConnectionType specifies the fully qualified type name for the System.Data.IDbConnection to use to connect to the database. The ConnectionString is database provider specific. The CommandText is either a prepared statement or a stored procedure, in this case it is a prepared statement. Each parameter to the prepared statement or stored procedure is specified with its name, database type and a layout that renders the value for the parameter.

The database table definition is:

  1. CREATE TABLE [dbo].[Log] (
  2. [Id] [int] IDENTITY (1, 1) NOT NULL,
  3. [Date] [datetime] NOT NULL,
  4. [Thread] [varchar] (255) NOT NULL,
  5. [Level] [varchar] (50) NOT NULL,
  6. [Logger] [varchar] (255) NOT NULL,
  7. [Message] [varchar] (4000) NOT NULL,
  8. [Exception] [varchar] (2000) NULL
  9. )

The appender configuration is:

  1. <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
  2. <bufferSize value="100" />
  3. <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  4. <connectionString value="data source=[database server];initial catalog=[database name];integrated security=false;persist security info=True;User ID=[user];Password=[password]" />
  5. <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
  6. <parameter>
  7. <parameterName value="@log_date" />
  8. <dbType value="DateTime" />
  9. <layout type="log4net.Layout.RawTimeStampLayout" />
  10. </parameter>
  11. <parameter>
  12. <parameterName value="@thread" />
  13. <dbType value="String" />
  14. <size value="255" />
  15. <layout type="log4net.Layout.PatternLayout">
  16. <conversionPattern value="%thread" />
  17. </layout>
  18. </parameter>
  19. <parameter>
  20. <parameterName value="@log_level" />
  21. <dbType value="String" />
  22. <size value="50" />
  23. <layout type="log4net.Layout.PatternLayout">
  24. <conversionPattern value="%level" />
  25. </layout>
  26. </parameter>
  27. <parameter>
  28. <parameterName value="@logger" />
  29. <dbType value="String" />
  30. <size value="255" />
  31. <layout type="log4net.Layout.PatternLayout">
  32. <conversionPattern value="%logger" />
  33. </layout>
  34. </parameter>
  35. <parameter>
  36. <parameterName value="@message" />
  37. <dbType value="String" />
  38. <size value="4000" />
  39. <layout type="log4net.Layout.PatternLayout">
  40. <conversionPattern value="%message" />
  41. </layout>
  42. </parameter>
  43. <parameter>
  44. <parameterName value="@exception" />
  45. <dbType value="String" />
  46. <size value="2000" />
  47. <layout type="log4net.Layout.ExceptionLayout" />
  48. </parameter>
  49. </appender>

MS Access

This example shows how to write events to an Access Database.

  1. <appender name="AdoNetAppender_Access" type="log4net.Appender.AdoNetAppender">
  2. <connectionString value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\log\access.mdb;User Id=;Password=;" />
  3. <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
  4. <parameter>
  5. <parameterName value="@log_date" />
  6. <dbType value="String" />
  7. <size value="255" />
  8. <layout type="log4net.Layout.PatternLayout">
  9. <conversionPattern value="%date" />
  10. </layout>
  11. </parameter>
  12. <parameter>
  13. <parameterName value="@thread" />
  14. <dbType value="String" />
  15. <size value="255" />
  16. <layout type="log4net.Layout.PatternLayout">
  17. <conversionPattern value="%thread" />
  18. </layout>
  19. </parameter>
  20. <parameter>
  21. <parameterName value="@log_level" />
  22. <dbType value="String" />
  23. <size value="50" />
  24. <layout type="log4net.Layout.PatternLayout">
  25. <conversionPattern value="%level" />
  26. </layout>
  27. </parameter>
  28. <parameter>
  29. <parameterName value="@logger" />
  30. <dbType value="String" />
  31. <size value="255" />
  32. <layout type="log4net.Layout.PatternLayout">
  33. <conversionPattern value="%logger" />
  34. </layout>
  35. </parameter>
  36. <parameter>
  37. <parameterName value="@message" />
  38. <dbType value="String" />
  39. <size value="1024" />
  40. <layout type="log4net.Layout.PatternLayout">
  41. <conversionPattern value="%message" />
  42. </layout>
  43. </parameter>
  44. </appender>

Oracle9i

This example shows how to write events to an Oracle9i Database.

The database table definition is:

  1. create table log (
  2. Datetime timestamp(3),
  3. Thread varchar2(255),
  4. Log_Level varchar2(255),
  5. Logger varchar2(255),
  6. Message varchar2(4000)
  7. );

The appender configuration is:

  1. <appender name="AdoNetAppender_Oracle" type="log4net.Appender.AdoNetAppender">
  2. <connectionType value="System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  3. <connectionString value="data source=[mydatabase];User ID=[user];Password=[password]" />
  4. <commandText value="INSERT INTO Log (Datetime,Thread,Log_Level,Logger,Message) VALUES (:log_date, :thread, :log_level, :logger, :message)" />
  5. <bufferSize value="128" />
  6. <parameter>
  7. <parameterName value=":log_date" />
  8. <dbType value="DateTime" />
  9. <layout type="log4net.Layout.RawTimeStampLayout" />
  10. </parameter>
  11. <parameter>
  12. <parameterName value=":thread" />
  13. <dbType value="String" />
  14. <size value="255" />
  15. <layout type="log4net.Layout.PatternLayout">
  16. <conversionPattern value="%thread" />
  17. </layout>
  18. </parameter>
  19. <parameter>
  20. <parameterName value=":log_level" />
  21. <dbType value="String" />
  22. <size value="50" />
  23. <layout type="log4net.Layout.PatternLayout">
  24. <conversionPattern value="%level" />
  25. </layout>
  26. </parameter>
  27. <parameter>
  28. <parameterName value=":logger" />
  29. <dbType value="String" />
  30. <size value="255" />
  31. <layout type="log4net.Layout.PatternLayout">
  32. <conversionPattern value="%logger" />
  33. </layout>
  34. </parameter>
  35. <parameter>
  36. <parameterName value=":message" />
  37. <dbType value="String" />
  38. <size value="4000" />
  39. <layout type="log4net.Layout.PatternLayout">
  40. <conversionPattern value="%message" />
  41. </layout>
  42. </parameter>
  43. </appender>

Oracle8i

This example shows how to write events to an Oracle8i Database.

The database table definition is:

  1. CREATE TABLE CSAX30.LOG
  2. (
  3. THREAD VARCHAR2(255),
  4. LOG_LEVEL VARCHAR2(255),
  5. LOGGER VARCHAR2(255),
  6. MESSAGE VARCHAR2(4000)
  7. )
  8. TABLESPACE CSAX30D LOGGING

The appender configuration is:

  1. <appender name="AdoNetAppender_Oracle" type="log4net.Appender.AdoNetAppender">
  2. <connectionType value ="System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  3. <connectionString value="data source=<dsname>;User ID=<userid>;Password=<password>" />
  4. <commandText value="INSERT INTO Log (Log_Level,Logger,Message) VALUES (:log_level, :logger, :message)" />
  5. <bufferSize value="250" />
  6. <parameter>
  7. <parameterName value=":log_level" />
  8. <layout type="log4net.Layout.PatternLayout">
  9. <conversionPattern value="%level" />
  10. </layout>
  11. </parameter>
  12. <parameter>
  13. <parameterName value=":logger" />
  14. <layout type="log4net.Layout.PatternLayout">
  15. <conversionPattern value="%logger" />
  16. </layout>
  17. </parameter>
  18. <parameter>
  19. <parameterName value=":message" />
  20. <dbType value="String" />
  21. <layout type="log4net.Layout.PatternLayout">
  22. <conversionPattern value="%message" />
  23. </layout>
  24. </parameter>
  25. </appender>

IBM DB2

This example shows how to write events to an IBM DB2 8.2 Database. The following syntax should also work with older DB2 database servers.

The database table definition is:

  1. CREATE TABLE "myschema.LOG" (
  2. "ID" INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (
  3. START WITH +1
  4. INCREMENT BY +1
  5. MINVALUE +1
  6. MAXVALUE +2147483647
  7. NO CYCLE
  8. NO CACHE
  9. NO ORDER
  10. ),
  11. "DATE" TIMESTAMP NOT NULL,
  12. "THREAD" VARCHAR(255) NOT NULL,
  13. "LEVEL" VARCHAR(500) NOT NULL,
  14. "LOGGER" VARCHAR(255) NOT NULL,
  15. "MESSAGE" VARCHAR(4000) NOT NULL,
  16. "EXCEPTION" VARCHAR(2000)
  17. )
  18. IN "LRGTABLES";

The appender configuration is:

  1. <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
  2. <bufferSize value="100" />
  3. <connectionType value="IBM.Data.DB2.DB2Connection,IBM.Data.DB2, Version=8.1.2.1" />
  4. <connectionString value="server=192.168.0.0;database=dbuser;user Id=username;password=password;persist security info=true" />
  5. <commandText value="INSERT INTO myschema.Log (Date,Thread,Level,Logger,Message,Exception) VALUES (@log_date,@thread,@log_level,@logger,@message,@exception)" />
  6. <parameter>
  7. <parameterName value="@log_date" />
  8. <dbType value="DateTime" />
  9. <layout type="log4net.Layout.RawTimeStampLayout" />
  10. </parameter>
  11. <parameter>
  12. <parameterName value="@thread" />
  13. <dbType value="String" />
  14. <size value="255" />
  15. <layout type="log4net.Layout.PatternLayout">
  16. <conversionPattern value="%thread" />
  17. </layout>
  18. </parameter>
  19. <parameter>
  20. <parameterName value="@log_level" />
  21. <dbType value="String" />
  22. <size value="500" />
  23. <layout type="log4net.Layout.PatternLayout">
  24. <conversionPattern value="%level" />
  25. </layout>
  26. </parameter>
  27. <parameter>
  28. <parameterName value="@logger" />
  29. <dbType value="String" />
  30. <size value="255" />
  31. <layout type="log4net.Layout.PatternLayout">
  32. <conversionPattern value="%logger" />
  33. </layout>
  34. </parameter>
  35. <parameter>
  36. <parameterName value="@message" />
  37. <dbType value="String" />
  38. <size value="4000" />
  39. <layout type="log4net.Layout.PatternLayout">
  40. <conversionPattern value="%message" />
  41. </layout>
  42. </parameter>
  43. <parameter>
  44. <parameterName value="@exception" />
  45. <dbType value="String" />
  46. <size value="2000" />
  47. <layout type="log4net.Layout.ExceptionLayout" />
  48. </parameter>
  49. </appender>

SQLite

This example shows how to write events to a SQLite Database. This was tested against v0.21 of the SQLite .NET provider.

SQLite doesn‘t have strongly-typed columns or field lengths but its recommended you still include this information for readability. The database table definition is:

  1. CREATE TABLE Log (
  2. LogId INTEGER PRIMARY KEY,
  3. Date DATETIME NOT NULL,
  4. Level VARCHAR(50) NOT NULL,
  5. Logger VARCHAR(255) NOT NULL,
  6. Message TEXT DEFAULT NULL
  7. );

The appender configuration is:

  1. <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
  2. <bufferSize value="100" />
  3. <connectionType value="Finisar.SQLite.SQLiteConnection, SQLite.NET, Version=0.21.1869.3794, Culture=neutral, PublicKeyToken=c273bd375e695f9c" />
  4. <connectionString value="Data Source=c:\\inetpub\\wwwroot\\logs\\log4net.db;Version=3;" />
  5. <commandText value="INSERT INTO Log (Date, Level, Logger, Message) VALUES (@Date, @Level, @Logger, @Message)" />
  6. <parameter>
  7. <parameterName value="@Date" />
  8. <dbType value="DateTime" />
  9. <layout type="log4net.Layout.RawTimeStampLayout" />
  10. </parameter>
  11. <parameter>
  12. <parameterName value="@Level" />
  13. <dbType value="String" />
  14. <layout type="log4net.Layout.PatternLayout">
  15. <conversionPattern value="%level" />
  16. </layout>
  17. </parameter>
  18. <parameter>
  19. <parameterName value="@Logger" />
  20. <dbType value="String" />
  21. <layout type="log4net.Layout.PatternLayout">
  22. <conversionPattern value="%logger" />
  23. </layout>
  24. </parameter>
  25. <parameter>
  26. <parameterName value="@Message" />
  27. <dbType value="String" />
  28. <layout type="log4net.Layout.PatternLayout">
  29. <conversionPattern value="%message" />
  30. </layout>
  31. </parameter>
  32. </appender>

AspNetTraceAppender

For full details see the SDK Reference entry: log4net.Appender.AspNetTraceAppender.

The following example shows how to configure the AspNetTraceAppender to log messages to the ASP.NET TraceContext. The messages are written to the System.Web.TraceContext.Write method if they are below level WARN. If they are WARN or above they are written to theSystem.Web.TraceContext.Warn method.

  1. <appender name="AspNetTraceAppender" type="log4net.Appender.AspNetTraceAppender" >
  2. <layout type="log4net.Layout.PatternLayout">
  3. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  4. </layout>
  5. </appender>

BufferingForwardingAppender

For full details see the SDK Reference entry: log4net.Appender.BufferingForwardingAppender.

The following example shows how to configure the BufferingForwardingAppender to buffer 100 messages before delivering them to the ConsoleAppender.

  1. <appender name="BufferingForwardingAppender" type="log4net.Appender.BufferingForwardingAppender" >
  2. <bufferSize value="100"/>
  3. <appender-ref ref="ConsoleAppender" />
  4. </appender>

This example shows how to deliver only significant events. A LevelEvaluator is specified with a threshold of WARN. This means that the events will only be delivered when a message with level of WARN or higher level is logged. Up to 512 (BufferSize) previous messages of any level will also be delivered to provide context information. Messages not sent will be discarded.

  1. <appender name="BufferingForwardingAppender" type="log4net.Appender.BufferingForwardingAppender" >
  2. <bufferSize value="512" />
  3. <lossy value="true" />
  4. <evaluator type="log4net.Core.LevelEvaluator">
  5. <threshold value="WARN"/>
  6. </evaluator>
  7. <appender-ref ref="ConsoleAppender" />
  8. </appender>

ColoredConsoleAppender

For full details see the SDK Reference entry: log4net.Appender.ColoredConsoleAppender.

The following example shows how to configure the ColoredConsoleAppender to log messages to the console. By default the messages are sent to the console standard output stream. This example shows how to highlight error messages.

  1. <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
  2. <mapping>
  3. <level value="ERROR" />
  4. <foreColor value="White" />
  5. <backColor value="Red, HighIntensity" />
  6. </mapping>
  7. <layout type="log4net.Layout.PatternLayout">
  8. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  9. </layout>
  10. </appender>

This example shows how to colorize multiple levels.

  1. <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
  2. <mapping>
  3. <level value="ERROR" />
  4. <foreColor value="White" />
  5. <backColor value="Red, HighIntensity" />
  6. </mapping>
  7. <mapping>
  8. <level value="DEBUG" />
  9. <backColor value="Green" />
  10. </mapping>
  11. <layout type="log4net.Layout.PatternLayout">
  12. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  13. </layout>
  14. </appender>

ConsoleAppender

For full details see the SDK Reference entry: log4net.Appender.ConsoleAppender.

The following example shows how to configure the ConsoleAppender to log messages to the console. By default the messages are sent to the console standard output stream.

  1. <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
  2. <layout type="log4net.Layout.PatternLayout">
  3. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  4. </layout>
  5. </appender>

This example shows how to direct the log messages to the console error stream.

  1. <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
  2. <target value="Console.Error" />
  3. <layout type="log4net.Layout.PatternLayout">
  4. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  5. </layout>
  6. </appender>

EventLogAppender

For full details see the SDK Reference entry: log4net.Appender.EventLogAppender.

The following example shows how to configure the EventLogAppender to log to the Application event log on the local machine using the event Source of the AppDomain.FriendlyName.

  1. <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
  2. <layout type="log4net.Layout.PatternLayout">
  3. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  4. </layout>
  5. </appender>

This example shows how to configure the EventLogAppender to use a specific event Source.

  1. <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
  2. <applicationName value="MyApp" />
  3. <layout type="log4net.Layout.PatternLayout">
  4. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  5. </layout>
  6. </appender>

For more information on how to setup the event log to allow the EventLogAppender to write to it, see the FAQ: Why doesn‘t the EventLogAppender work?.

FileAppender

For full details see the SDK Reference entry: log4net.Appender.FileAppender.

The following example shows how to configure the FileAppender to write messages to a file. The file specified is log-file.txt. The file will be appended to rather than overwritten each time the logging process starts.

  1. <appender name="FileAppender" type="log4net.Appender.FileAppender">
  2. <file value="log-file.txt" />
  3. <appendToFile value="true" />
  4. <layout type="log4net.Layout.PatternLayout">
  5. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  6. </layout>
  7. </appender>

This example shows how to configure the file name to write to using an environment variable TMP. The encoding to use to write to the file is also specified.

  1. <appender name="FileAppender" type="log4net.Appender.FileAppender">
  2. <file value="${TMP}\log-file.txt" />
  3. <appendToFile value="true" />
  4. <encoding value="unicodeFFFE" />
  5. <layout type="log4net.Layout.PatternLayout">
  6. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  7. </layout>
  8. </appender>

This example shows how to configure the appender to use the minimal locking model that allows multiple processes to write to the same file.

  1. <appender name="FileAppender" type="log4net.Appender.FileAppender">
  2. <file value="${TMP}\log-file.txt" />
  3. <appendToFile value="true" />
  4. <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
  5. <layout type="log4net.Layout.PatternLayout">
  6. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  7. </layout>
  8. </appender>

This example shows how to configure the appender to use the "inter process" locking model.

  1. <appender name="FileAppender" type="log4net.Appender.FileAppender">
  2. <file value="${TMP}\log-file.txt" />
  3. <appendToFile value="true" />
  4. <lockingModel type="log4net.Appender.FileAppender+InterProcessLock" />
  5. <layout type="log4net.Layout.PatternLayout">
  6. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  7. </layout>
  8. </appender>

Before you change the locking model so that multiple process may log to the same file, please read the FAQ.

ForwardingAppender

For full details see the SDK Reference entry: log4net.Appender.ForwardingAppender.

The following example shows how to configure the ForwardingAppender. The forwarding appender allows a set of constraints to be used to decorate an appender. In this example the ConsoleAppender is decorated with a Threshold of level WARN. This means that an event directed to the ConsoleAppender directly will be logged regardless of its level, but an event directed to the ForwardingAppender will only be passed on to the ConsoleAppender if its level is WARN or higher. This appender is used only in special circumstances.

  1. <appender name="ForwardingAppender" type="log4net.Appender.ForwardingAppender" >
  2. <threshold value="WARN"/>
  3. <appender-ref ref="ConsoleAppender" />
  4. </appender>

ManagedColoredConsoleAppender

For full details see the SDK Reference entry: log4net.Appender.ManagedColoredConsoleAppender.

The following example shows how to configure the ManagedColoredConsoleAppender to log messages to the console. By default the messages are sent to the console standard output stream. This example shows how to highlight error messages.

  1. <appender name="ManagedColoredConsoleAppender" type="log4net.Appender.ManagedColoredConsoleAppender">
  2. <mapping>
  3. <level value="ERROR" />
  4. <foreColor value="White" />
  5. <backColor value="Red" />
  6. </mapping>
  7. <layout type="log4net.Layout.PatternLayout">
  8. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  9. </layout>
  10. </appender>

This example shows how to colorize multiple levels.

  1. <appender name="ManagedColoredConsoleAppender" type="log4net.Appender.ManagedColoredConsoleAppender">
  2. <mapping>
  3. <level value="ERROR" />
  4. <foreColor value="DarkRed" />
  5. </mapping>
  6. <mapping>
  7. <level value="WARN" />
  8. <foreColor value="Yellow" />
  9. </mapping>
  10. <mapping>
  11. <level value="INFO" />
  12. <foreColor value="White" />
  13. </mapping>
  14. <mapping>
  15. <level value="DEBUG" />
  16. <foreColor value="Blue" />
  17. </mapping>
  18. <layout type="log4net.Layout.PatternLayout">
  19. <conversionPattern value="%date %-5level %-20.20logger: %message%newline"/>
  20. </layout>
  21. </appender>

MemoryAppender

For full details see the SDK Reference entry: log4net.Appender.MemoryAppender.

It is unlikely that the MemoryAppender will be configured using a config file, but if you want to do it here‘s how.

  1. <appender name="MemoryAppender" type="log4net.Appender.MemoryAppender">
  2. <onlyFixPartialEventData value="true" />
  3. </appender>

NetSendAppender

For full details see the SDK Reference entry: log4net.Appender.NetSendAppender.

The following example shows how to configure the NetSendAppender to deliver messages to a specific user‘s screen. As this appender is typically only used for important notifications a Threshold of level Error is specified. This example delivers the messages to the user nicko on the machine SQUARE. However things are not always straight forward using the Windows Messenger Service, one possible outcome using this configuration is that the Serverwill broadcast looking for a WINS server which it will then ask to deliver the message to the Recipient, the WINS server will deliver it to the first terminal that the user logged in from.

  1. <appender name="NetSendAppender" type="log4net.Appender.NetSendAppender">
  2. <threshold value="ERROR" />
  3. <server value="SQUARE" />
  4. <recipient value="nicko" />
  5. <layout type="log4net.Layout.PatternLayout">
  6. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  7. </layout>
  8. </appender>

OutputDebugStringAppender

For full details see the SDK Reference entry: log4net.Appender.OutputDebugStringAppender.

The following example shows how to configure the OutputDebugStringAppender to write logging messages to the OutputDebugString API.

  1. <appender name="OutputDebugStringAppender" type="log4net.Appender.OutputDebugStringAppender" >
  2. <layout type="log4net.Layout.PatternLayout">
  3. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  4. </layout>
  5. </appender>

RemotingAppender

For full details see the SDK Reference entry: log4net.Appender.RemotingAppender.

The following example shows how to configure the RemotingAppender to deliver logging events to a specified Sink (in this example the sink is tcp://localhost:8085/LoggingSink). In this example the events are delivered in blocks of 95 events because of the BufferSize. No events are discarded. The OnlyFixPartialEventData option allows the appender to ignore certain logging event properties that can be very slow to generate (e.g. the calling location information).

  1. <appender name="RemotingAppender" type="log4net.Appender.RemotingAppender" >
  2. <sink value="tcp://localhost:8085/LoggingSink" />
  3. <lossy value="false" />
  4. <bufferSize value="95" />
  5. <onlyFixPartialEventData value="true" />
  6. </appender>

This example configures the RemotingAppender to deliver the events only when an event with level ERROR or above is logged. When the events are delivered, up to 200 (BufferSize) previous events (regardless of level) will be delivered to provide context. Events not delivered will be discarded.

  1. <appender name="RemotingAppender" type="log4net.Appender.RemotingAppender" >
  2. <sink value="tcp://localhost:8085/LoggingSink" />
  3. <lossy value="true" />
  4. <bufferSize value="200" />
  5. <onlyFixPartialEventData value="true" />
  6. <evaluator type="log4net.Core.LevelEvaluator">
  7. <threshold value="ERROR"/>
  8. </evaluator>
  9. </appender>

RollingFileAppender

For full details see the SDK Reference entry: log4net.Appender.RollingFileAppender.

The RollingFileAppender builds on the FileAppender and has the same options as that appender.

The following example shows how to configure the RollingFileAppender to write to the file log.txt. The file written to will always be called log.txt because the StaticLogFileName param is specified. The file will be rolled based on a size constraint (RollingStyle). Up to 10 (MaxSizeRollBackups) old files of 100 KB each (MaximumFileSize) will be kept. These rolled files will be named: log.txt.1log.txt.2log.txt.3, etc...

  1. <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
  2. <file value="log.txt" />
  3. <appendToFile value="true" />
  4. <rollingStyle value="Size" />
  5. <maxSizeRollBackups value="10" />
  6. <maximumFileSize value="100KB" />
  7. <staticLogFileName value="true" />
  8. <layout type="log4net.Layout.PatternLayout">
  9. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  10. </layout>
  11. </appender>

This example show how to configure the RollingFileAppender to roll log files on a date period. This example will roll the log file every minute! To change the rolling period adjust the DatePattern value. For example, a date pattern of "yyyyMMdd" will roll every day. See System.Globalization.DateTimeFormatInfo for a list of available patterns.

  1. <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  2. <file value="logfile" />
  3. <appendToFile value="true" />
  4. <rollingStyle value="Date" />
  5. <datePattern value="yyyyMMdd-HHmm" />
  6. <layout type="log4net.Layout.PatternLayout">
  7. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  8. </layout>
  9. </appender>

This example show how to configure the RollingFileAppender to roll log files on a date period and within a date period on file size. For each day only the last 10 files of 1MB will be kept.

  1. <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  2. <file value="logfile" />
  3. <appendToFile value="true" />
  4. <rollingStyle value="Composite" />
  5. <datePattern value="yyyyMMdd" />
  6. <maxSizeRollBackups value="10" />
  7. <maximumFileSize value="1MB" />
  8. <layout type="log4net.Layout.PatternLayout">
  9. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  10. </layout>
  11. </appender>

This example show how to configure the RollingFileAppender to roll log files once per program execution. The appendToFile property is set to false to prevent the appender from overwriting the existing files. The maxSizeRollBackups is set to negative 1 to allow an infinite number of backup files. The file size does have to be limited but here it is set to 50 Gigabytes which, if a log file exceeds this size limit during a single run then it will also be rolled.

  1. <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  2. <file value="logfile.txt" />
  3. <appendToFile value="false" />
  4. <rollingStyle value="Size" />
  5. <maxSizeRollBackups value="-1" />
  6. <maximumFileSize value="50GB" />
  7. <layout type="log4net.Layout.PatternLayout">
  8. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  9. </layout>
  10. </appender>

SmtpAppender

For full details see the SDK Reference entry: log4net.Appender.SmtpAppender.

The following example shows how to configure the SmtpAppender to deliver log events via SMTP email. The ToFromSubject and SmtpHost are required parameters. This example shows how to deliver only significant events. A LevelEvaluator is specified with a threshold of WARN. This means that an email will be sent for each WARN or higher level message that is logged. Each email will also contain up to 512 (BufferSize) previous messages of any level to provide context. Messages not sent will be discarded.

  1. <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
  2. <to value="[email protected]" />
  3. <from value="[email protected]" />
  4. <subject value="test logging message" />
  5. <smtpHost value="SMTPServer.domain.com" />
  6. <bufferSize value="512" />
  7. <lossy value="true" />
  8. <evaluator type="log4net.Core.LevelEvaluator">
  9. <threshold value="WARN"/>
  10. </evaluator>
  11. <layout type="log4net.Layout.PatternLayout">
  12. <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
  13. </layout>
  14. </appender>

This example shows how to configure the SmtpAppender to deliver all messages in emails with 512 (BufferSize) messages per email.

  1. <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
  2. <to value="[email protected]" />
  3. <from value="[email protected]" />
  4. <subject value="test logging message" />
  5. <smtpHost value="SMTPServer.domain.com" />
  6. <bufferSize value="512" />
  7. <lossy value="false" />
  8. <layout type="log4net.Layout.PatternLayout">
  9. <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
  10. </layout>
  11. </appender>

This example shows a more verbose formatting layout for the mail messages.

  1. <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender,log4net">
  2. <to value="[email protected]" />
  3. <from value="[email protected]" />
  4. <subject value="test logging message" />
  5. <smtpHost value="SMTPServer.domain.com" />
  6. <bufferSize value="512" />
  7. <lossy value="false" />
  8. <evaluator type="log4net.Core.LevelEvaluator,log4net">
  9. <threshold value="WARN" />
  10. </evaluator>
  11. <layout type="log4net.Layout.PatternLayout,log4net">
  12. <conversionPattern value="%property{log4net:HostName} :: %level :: %message %newlineLogger: %logger%newlineThread: %thread%newlineDate: %date%newlineNDC: %property{NDC}%newline%newline" />
  13. </layout>
  14. </appender>

SmtpPickupDirAppender

For full details see the SDK Reference entry: log4net.Appender.SmtpPickupDirAppender.

The SmtpPickupDirAppender is configured similarly to the SmtpAppender. The only difference is that rather than specify a SmtpHost parameter a PickupDir must be specified.

The PickupDir parameter is a path that must exist and the code executing the appender must have permission to create new files and write to them in this directory. The path is relative to the application‘s base directory (AppDomain.BaseDirectory).

The following example shows how to configure the SmtpPickupDirAppender to deliver log events via SMTP email. The ToFromSubject and PickupDirare required parameters. This example shows how to deliver only significant events. A LevelEvaluator is specified with a threshold of WARN. This means that an email will be sent for each WARN or higher level message that is logged. Each email will also contain up to 512 (BufferSize) previous messages of any level to provide context. Messages not sent will be discarded.

  1. <appender name="SmtpPickupDirAppender" type="log4net.Appender.SmtpPickupDirAppender">
  2. <to value="[email protected]" />
  3. <from value="[email protected]" />
  4. <subject value="test logging message" />
  5. <pickupDir value="C:\SmtpPickup" />
  6. <bufferSize value="512" />
  7. <lossy value="true" />
  8. <evaluator type="log4net.Core.LevelEvaluator">
  9. <threshold value="WARN"/>
  10. </evaluator>
  11. <layout type="log4net.Layout.PatternLayout">
  12. <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
  13. </layout>
  14. </appender>

TraceAppender

For full details see the SDK Reference entry: log4net.Appender.TraceAppender.

The following example shows how to configure the TraceAppender to log messages to the System.Diagnostics.Trace system. This is the tracing system supplied with the .net base class libraries. See the MSDN documentation for the System.Diagnostics.Trace class for more details on how to configure the trace system.

  1. <appender name="TraceAppender" type="log4net.Appender.TraceAppender">
  2. <layout type="log4net.Layout.PatternLayout">
  3. <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  4. </layout>
  5. </appender>

UdpAppender

For full details see the SDK Reference entry: log4net.Appender.UdpAppender.

The following example shows how to configure the UdpAppender to send events to a RemoteAddress on the specified RemotePort.

  1. <appender name="UdpAppender" type="log4net.Appender.UdpAppender">
  2. <localPort value="8080" />
  3. <remoteAddress value="224.0.0.1" />
  4. <remotePort value="8080" />
  5. <layout type="log4net.Layout.PatternLayout, log4net">
  6. <conversionPattern value="%-5level %logger [%property{NDC}] - %message%newline" />
  7. </layout>
  8. </appender>

DynamicPatternLayout

For full details see the SDK Reference entry: log4net.Layout.DynamicPatternLayout.

The DynamicPatternLayout should be used whenever the header or footer should contain information that could change over time. Compared to the static PatternLayout which does not re-evaluate on every invoke, the DynamicPatternLayout does re-evaluate the pattern on every invoke. It does, for example, allow to include the current DateTime in the header and/or the footer which was not possible with the static PatternLayout.

The following example shows how to configure the DynamicPatternLayout.

  1. <layout type="log4net.Layout.DynamicPatternLayout">
  2. <param name="Header" value="%newline**** Trace Opened Local: %date{yyyy-MM-dd HH:mm:ss.fff} UTC: %utcdate{yyyy-MM-dd HH:mm:ss.fff} ****%newline"/>
  3. <param name="Footer" value="**** Trace Closed %date{yyyy-MM-dd HH:mm:ss.fff} ****%newline"/>
  4. </layout>

原文地址:https://www.cnblogs.com/zhaooyw/p/8443680.html

时间: 2024-10-09 03:04:13

Log4NET将日志写入数据库中的相关文章

如何借助log4j把日志写入数据库中

log4j是一个优秀的开源日志记录项目,我们不仅可以对输出的日志的格式自定义,还可以自己定义日志输出的目的地,比如:屏幕,文本文件,数据 库,甚至能通过socket输出.本节使用MySQL数据库主要讲述如何将日志信息输入到数据库中. 用log4j将日志写入数据库主要用到是log4j包下的JDBCAppender类,它提供了将日志信息异步写入数据的功能,我们可以直接使用这个类将我 们的日志信息写入数据库:也可以扩展JDBCAppender类,就是将JDBCAppender类作为基类进行二次开发获得

c#用log4Net将日志写入到Oracle数据库,并写入到文件中

原文:c#用log4Net将日志写入到Oracle数据库,并写入到文件中 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/weixin_37913923/article/details/79072898 1.从官网下载log4net包,安装到项目中: 2.配置文件log4net.config/app.config <?xml version="1.0" encoding=&

Log4Net的应用教程之保存日志到数据库中

关于Log4Net的应用,网上有很多教程,但大多数都是拷贝复制,有些按照他的代码来,运行起来发现也出不来效果,但是Log4net的作用实在是非常大的,或者这里说的不对,应该说系统的日志功能是很重要的也很有必要的,当然设置系统的时候完全可以自己来开发一个日志功能,不外乎就是写日志到文件或者数据库中等等,如果写日志到数据库中,那么就需要使用ADO了,如果是三层架构的,那么这个日志添加就不能再任何地方都可以随便添加了,但是Log4net可以做到独立的链接数据库,并且在系统的任何地方都能够使用. 01

使用log4j让日志写入数据库

之前做的一个项目有这么个要求,在日志管理系统里,需要将某些日志信息存储到数据库里,供用户.管理员查看分析.因此我就花了点时间搞了一下这一功能,各位请看. 摘要:我们知道log4j能提供强大的可配置的记日志功能,有写文件的.打印到控制台的等等,但有时我们需要它把日志输出到后台数据库中,log4j的强大的可扩展性支持了这一点,以下就是具体的实现. 关键词:log,log4j,日志,Java,DB,数据库,slf4j 前提:已经配置好slf4j.log4j,能正常的往文件或控制台写日志. 需求:将日志

logback日志写入数据库(mysql)配置

如题  建议将日志级别设置为ERROR.这样可以避免存储过多的数据到数据中. 1  logback 配置文件(如下) <?xml version="1.0" encoding="UTF-8" ?> <configuration scan="true"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender&q

log4net 添加自定义日志到数据库

添加操作日志到数据库举例: (一)建立数据库的操作日志表,如下我建立了一个简单的日志表 (二)配置文件中的配置如下 <log4net> <!--错误日志记录数据库--> <logger name="OperateDB"> <level value="INFO"/> <appender-ref ref="AdoNetAppender_OperToSql" /> </logger>

将日志写入数据库

之前做的一个项目有这么个要求,在日志管理系统里,需要将某些日志信息存储到数据库里,供用户.管理员查看分析.因此我就花了点时间搞了一下这一功能,各位请看. 摘要:我们知道log4j能提供强大的可配置的记日志功能,有写文件的.打印到控制台的等等,但有时我们需要它把日志输出到后台数据库中,log4j的强大的可扩展性支持了这一点,以下就是具体的实现. 关键词:log,log4j,日志,Java,DB,数据库,slf4j 前提:已经配置好slf4j.log4j,能正常的往文件或控制台写日志. 需求:将日志

【.NET】Log4net将操作日志写入数据库

配置文件可以参考上篇博文[.NET]log4net配置文件解析. 先在Global.aspx中添加这样一句代码,来读取配置文件,初始化log4net的环境. public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { log4net.Config.XmlConfigurator.Configure(); } 新建一个Log文件夹,

用log4j将日志写入数据库

以下为log4j中的配置参数: %m 输出代码中指定的消息 %p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL %r 输出自应用启动到输出该log信息耗费的毫秒数 %t 输出产生该日志事件的线程名: %n 输出一个回车换行符,Windows平台为"\r\n",Unix平台为"\n" %d 输出日志时间的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss,SSS},输出类似:2008年