Click or drag to resize

DatabaseTarget Class

Writes log messages to the database using an ADO.NET provider.
Inheritance Hierarchy
SystemObject
  NLog.TargetsTarget
    NLog.TargetsDatabaseTarget

Namespace:  NLog.Targets
Assembly:  NLog.Database (in NLog.Database.dll) Version: 5.3.4+73d83d3161d31288ca5c554cc50d27b6bed5f28b
Syntax
public class DatabaseTarget : Target, 
	IInstallable

The DatabaseTarget type exposes the following members.

Constructors
  NameDescription
Public methodDatabaseTarget
Initializes a new instance of the DatabaseTarget class.
Public methodDatabaseTarget(String)
Initializes a new instance of the DatabaseTarget class.
Top
Properties
  NameDescription
Public propertyCommandProperties
Gets the collection of properties. Each item contains a mapping between NLog layout and a property on the DbCommand instance
Public propertyCommandText
Gets or sets the text of the SQL command to be run on each log level.
Public propertyCommandType
Gets or sets the type of the SQL command to be run on each log level.
Public propertyConnectionProperties
Gets the collection of properties. Each item contains a mapping between NLog layout and a property on the DbConnection instance
Public propertyConnectionString
Gets or sets the connection string. When provided, it overrides the values specified in DBHost, DBUserName, DBPassword, DBDatabase.
Public propertyConnectionStringName
Gets or sets the name of the connection string (as specified in <connectionStrings> configuration section.
Public propertyDBDatabase
Gets or sets the database name. If the ConnectionString is not provided this value will be used to construct the "Database=" part of the connection string.
Public propertyDBHost
Gets or sets the database host name. If the ConnectionString is not provided this value will be used to construct the "Server=" part of the connection string.
Public propertyDBPassword
Gets or sets the database password. If the ConnectionString is not provided this value will be used to construct the "Password=" part of the connection string.
Public propertyDBProvider
Gets or sets the name of the database provider.
Public propertyDBUserName
Gets or sets the database user name. If the ConnectionString is not provided this value will be used to construct the "User ID=" part of the connection string.
Public propertyInstallConnectionString
Gets or sets the connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used.
Public propertyInstallDdlCommands
Gets the installation DDL commands.
Protected propertyIsInitialized
Gets a value indicating whether the target has been initialized.
(Inherited from Target.)
Public propertyIsolationLevel
Configures isolated transaction batch writing. If supported by the database, then it will improve insert performance.
Public propertyKeepConnection
Gets or sets a value indicating whether to keep the database connection open between the log events.
Protected propertyLoggingConfiguration
Gets the logging configuration this target is part of.
(Inherited from Target.)
Public propertyName
Gets or sets the name of the target.
(Inherited from Target.)
Public propertyParameters
Gets the collection of parameters. Each item contains a mapping between NLog layout and a database named or positional parameter.
Protected propertySyncRoot
Gets the object which can be used to synchronize asynchronous operations that must rely on the .
(Inherited from Target.)
Public propertyUninstallDdlCommands
Gets the uninstallation DDL commands.
Top
Methods
  NameDescription
Protected methodBuildConnectionString
Build the connectionstring from the properties.
Protected methodCloseTarget
Closes the target to release any initialized resources
(Overrides TargetCloseTarget.)
Protected methodCreateDatabaseParameter
Create database parameter
Public methodDispose
Closes the target.
(Inherited from Target.)
Protected methodDispose(Boolean)
Releases unmanaged and - optionally - managed resources.
(Inherited from Target.)
Public methodFlush
Flush any pending log messages (in case of asynchronous targets).
(Inherited from Target.)
Protected methodFlushAsync
Flush any pending log messages
(Inherited from Target.)
Protected methodGetDatabaseParameterValue
Extract parameter value from the logevent
Protected methodInitializeTarget
Initializes the target before writing starts
(Overrides TargetInitializeTarget.)
Public methodInstall
Performs installation which requires administrative permissions.
Public methodIsInstalled
Determines whether the item is installed.
Public methodPrecalculateVolatileLayouts
Calls the Precalculate(LogEventInfo) on each volatile layout used by this target. This method won't prerender if all layouts in this target are thread-agnostic.
(Inherited from Target.)
Protected methodRenderLogEvent(Layout, LogEventInfo)
Renders the logevent into a string-result using the provided layout
(Inherited from Target.)
Protected methodRenderLogEventT(LayoutT, LogEventInfo, T)
Renders the logevent into a result-value by using the provided layout
(Inherited from Target.)
Protected methodResolveServiceT
Resolve from DI ServiceRepository
(Inherited from Target.)
Public methodToString
Returns a string that represents the current object.
(Inherited from Target.)
Public methodUninstall
Performs uninstallation which requires administrative permissions.
Protected methodWrite(AsyncLogEventInfo)
Writes async log event to the log target.
(Inherited from Target.)
Protected methodWrite(IListAsyncLogEventInfo)
Writes an array of logging events to the log target. By default it iterates on all events and passes them to "Write" method. Inheriting classes can use this method to optimize batch writes.
(Overrides TargetWrite(IListAsyncLogEventInfo).)
Protected methodWrite(LogEventInfo)
Writes the specified logging event to the database. It creates a new database command, prepares parameters for it by calculating layouts and executes the command.
(Overrides TargetWrite(LogEventInfo).)
Public methodWriteAsyncLogEvent
Writes the log to the target.
(Inherited from Target.)
Public methodWriteAsyncLogEvents(AsyncLogEventInfo)
Writes the array of log events.
(Inherited from Target.)
Public methodWriteAsyncLogEvents(IListAsyncLogEventInfo)
Writes the array of log events.
(Inherited from Target.)
Protected methodWriteAsyncThreadSafe(AsyncLogEventInfo)
Writes a log event to the log target, in a thread safe manner. Any override of this method has to provide their own synchronization mechanism. !WARNING! Custom targets should only override this method if able to provide their own synchronization mechanism. Layout-objects are not guaranteed to be thread-safe, so using them without a SyncRoot-object can be dangerous.
(Inherited from Target.)
Protected methodWriteAsyncThreadSafe(IListAsyncLogEventInfo)
Writes an array of logging events to the log target, in a thread safe manner. Any override of this method has to provide their own synchronization mechanism. !WARNING! Custom targets should only override this method if able to provide their own synchronization mechanism. Layout-objects are not guaranteed to be thread-safe, so using them without a SyncRoot-object can be dangerous.
(Inherited from Target.)
Protected methodWriteFailedNotInitialized
LogEvent is written to target, but target failed to successfully initialize
(Inherited from Target.)
Top
Remarks

Note .NET Core application cannot load connectionstrings from app.config / web.config. Instead use ${configsetting}

See NLog Wiki
Examples

The configuration is dependent on the database type, because there are different methods of specifying connection string, SQL command and command parameters.

MS SQL Server using System.Data.SqlClient:

XML
 1<?xml version="1.0" ?>
 2<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4      autoReload="true">
 5    <targets>
 6        <target name="database" xsi:type="Database">
 7
 8            <dbProvider>mssql</dbProvider>
 9
10            <!-- database connection parameters -->
11            <!-- alternatively you could provide a single 'connectionstring' parameter -->
12
13            <dbHost>.</dbHost> 
14            <dbDatabase>NLogDatabase</dbDatabase>
15            <dbUsername>nloguser</dbUsername>
16            <dbPassword>nlogpassword</dbPassword>
17
18            <commandText>
19                insert into LogTable(time_stamp,level,logger,message) values(@time_stamp, @level, @logger, @message);
20            </commandText>
21
22            <parameter name="@time_stamp" layout="${date}" />
23            <parameter name="@level" layout="${level}" />
24            <parameter name="@logger" layout="${logger}" />
25            <parameter name="@message" layout="${message}" />
26        </target>
27    </targets>
28
29    <rules>
30        <logger name="*" minlevel="Debug" writeTo="database" />
31    </rules>
32</nlog>

Oracle using System.Data.OracleClient:

XML
 1<?xml version="1.0" ?>
 2<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 4
 5    <!-- configuration contributed by David Maly -->
 6
 7    <targets>
 8        <target name="database" xsi:type="Database" keepConnection="false"
 9                dbProvider="System.Data.OracleClient.OracleConnection,System.Data.OracleClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
10                connectionString="Data Source=MYORACLEDB;User Id=DBO;Password=MYPASSWORD;Integrated Security=no;"
11                commandText="insert into LOGTABLE( TIME_STAMP,LOGLEVEL,LOGGER,CALLSITE,MESSAGE) values( :TIME_STAMP,:LOGLEVEL,:LOGGER,:CALLSITE,:MESSAGE)">
12            <parameter name="TIME_STAMP" layout="${longdate}" />
13            <parameter name="LOGLEVEL" layout="${level:uppercase=true}" />
14            <parameter name="LOGGER" layout="${logger}" />
15            <parameter name="CALLSITE" layout="${callsite:filename=true}" />
16            <parameter name="MESSAGE" layout="${message}" />
17        </target>
18    </targets>
19
20    <rules>
21        <logger name="*" minlevel="Debug" writeTo="database" />
22    </rules>
23</nlog>

Oracle using System.Data.OleDBClient:

XML
 1<?xml version="1.0" ?>
 2<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 4
 5    <!-- configuration contributed by David Maly -->
 6
 7    <targets>
 8        <target name="database" xsi:type="Database" keepConnection="false" dbProvider="oledb"
 9            connectionString="Provider=msdaora;Data Source=MYORACLEDB;User Id=DBO;Password=MYPASSWORD;"
10            commandText="insert into LOGTABLE( TIME_STAMP,LOGLEVEL,LOGGER,CALLSITE,MESSAGE) values(?,?,?,?,?)">
11            <parameter name="TIME_STAMP" layout="${longdate}" />
12            <parameter name="LOGLEVEL" layout="${level:uppercase=true}" />
13            <parameter name="LOGGER" layout="${logger}" />
14            <parameter name="CALLSITE" layout="${callsite:filename=true}" />
15            <parameter name="MESSAGE" layout="${message}" />
16        </target>
17    </targets>
18
19    <rules>
20        <logger name="*" minlevel="Debug" writeTo="database" />
21    </rules>
22</nlog>

To set up the log target programmatically use code like this (an equivalent of MSSQL configuration):

C#
 1using NLog;
 2using NLog.Targets;
 3
 4class Example
 5{
 6    static void Main(string[] args)
 7    {
 8        DatabaseTarget target = new DatabaseTarget();
 9        DatabaseParameterInfo param;
10
11        target.DBProvider = "mssql";
12        target.DBHost = ".";
13        target.DBUserName = "nloguser";
14        target.DBPassword = "pass";
15        target.DBDatabase = "databasename";
16        target.CommandText = "insert into LogTable(time_stamp,level,logger,message) values(@time_stamp, @level, @logger, @message);";
17
18        param = new DatabaseParameterInfo();
19        param.Name = "@time_stamp";
20        param.Layout = "${date}";
21        target.Parameters.Add(param);
22
23        param = new DatabaseParameterInfo();
24        param.Name = "@level";
25        param.Layout = "${level}";
26        target.Parameters.Add(param);
27
28        param = new DatabaseParameterInfo();
29        param.Name = "@logger";
30        param.Layout = "${logger}";
31        target.Parameters.Add(param);
32
33        param = new DatabaseParameterInfo();
34        param.Name = "@message";
35        param.Layout = "${message}";
36        target.Parameters.Add(param);
37
38        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
39
40        Logger logger = LogManager.GetLogger("Example");
41        logger.Debug("log message");
42    }
43}
See Also