public void DatabaseExceptionTest1() { MockDbConnection.ClearLog(); var exceptions = new List<Exception>(); var db = new DatabaseTarget(); db.CommandText = "not important"; db.ConnectionString = "cannotconnect"; db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; db.Initialize(null); db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); db.Close(); Assert.Equal(1, exceptions.Count); Assert.NotNull(exceptions[0]); Assert.Equal("Cannot open fake database.", exceptions[0].Message); Assert.Equal("Open('cannotconnect').\r\n", MockDbConnection.Log); }
public void SimpleDatabaseTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "FooBar", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, }; dt.Initialize(null); Assert.AreSame(typeof(MockDbConnection), dt.ConnectionType); List<Exception> exceptions = new List<Exception>(); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add)); foreach (var ex in exceptions) { Assert.IsNull(ex, Convert.ToString(ex)); } string expectedLog = @"Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') Close() Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') Close() Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') Close() "; AssertLog(expectedLog); }
static void Main(string[] args) { DatabaseTarget target = new DatabaseTarget(); DatabaseParameterInfo param; target.DBProvider = "oledb"; target.ConnectionString = "Provider=msdaora;Data Source=MYORACLEDB;User Id=DBO;Password=MYPASSWORD;"; target.CommandText = "insert into LOGTABLE( TIME_STAMP,LOGLEVEL,LOGGER,CALLSITE,MESSAGE) values(?,?,?,?,?)"; target.Parameters.Add(new DatabaseParameterInfo("TIME_STAMP", "${longdate}")); target.Parameters.Add(new DatabaseParameterInfo("LOGLEVEL", "${level:uppercase=true}")); target.Parameters.Add(new DatabaseParameterInfo("LOGGER", "${logger}")); target.Parameters.Add(new DatabaseParameterInfo("CALLSITE", "${callsite:filename=true}")); target.Parameters.Add(new DatabaseParameterInfo("MESSAGE", "${message}")); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); }
static void Main(string[] args) { DatabaseTarget target = new DatabaseTarget(); target.DBProvider = "System.Data.OracleClient.OracleConnection,System.Data.OracleClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; target.ConnectionString = "Data Source=MYORACLEDB;User Id=DBO;Password=MYPASSWORD;Integrated Security=no;"; target.CommandText = "insert into LOGTABLE( TIME_STAMP,LOGLEVEL,LOGGER,CALLSITE,MESSAGE) values( :TIME_STAMP,:LOGLEVEL,:LOGGER,:CALLSITE,:MESSAGE)"; target.KeepConnection = true; target.Parameters.Add(new DatabaseParameterInfo("TIME_STAMP", "${longdate}")); target.Parameters.Add(new DatabaseParameterInfo("LOGLEVEL", "${level:uppercase=true}")); target.Parameters.Add(new DatabaseParameterInfo("LOGGER", "${logger}")); target.Parameters.Add(new DatabaseParameterInfo("CALLSITE", "${callsite:filename=true}")); target.Parameters.Add(new DatabaseParameterInfo("MESSAGE", "${message}")); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); }
private static void ConfigureLogger(IAuditConfiguration configuration) { var config = new LoggingConfiguration(); var databaseTarget = new NLog.Targets.DatabaseTarget { ConnectionString = configuration.AuditDataConnection, CommandText = @" INSERT INTO [v2].[ApplicationLog]([Level], [Type], [Message]) VALUES(@level, @type, @message);" }; databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = "@level", Layout = "${level}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = "@type", Layout = "${exception:format=type}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = "@message", Layout = "${message:exceptionSeparator=->:withException=true}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = "@stackTrace", Layout = "${exception:format=stackTrace}" }); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Error, databaseTarget)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Warn, databaseTarget)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, databaseTarget)); var fileTarget = new FileTarget { FileName = $@"logs\errors_{DateTime.Now:yyyyMMdd}.log", Layout = Layout.FromString("${message:exceptionSeparator=->:withException=true}") }; config.LoggingRules.Add(new LoggingRule("*", LogLevel.Error, fileTarget)); NLog.LogManager.Configuration = config; }
public static LoggingConfiguration Create(string connectionString, TraceLogLevel traceLogLevel) { var config = new LoggingConfiguration(); var databaseTarget = new DatabaseTarget(); config.AddTarget("database", databaseTarget); databaseTarget.ConnectionString = connectionString; databaseTarget.CommandText = @" INSERT INTO [dbo].[TraceLogs] ( [Logger], [Level], [ThreadId], [MachineName], [Message] ) VALUES ( @Logger, @Level, @ThreadId, @MachineName, @Message ); "; databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Logger", new SimpleLayout("${logger}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Level", new SimpleLayout("${uppercase:${level}}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@ThreadId", new SimpleLayout("${threadid}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@MachineName", new SimpleLayout("${machinename}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@CallSite", new SimpleLayout("${callsite}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@UserName", new SimpleLayout("${identity}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Message", new SimpleLayout("${message}"))); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@StackTrace", new SimpleLayout("${exception:format=tostring}"))); var loggingRule = new LoggingRule("*", traceLogLevel.ToNLogLevel(), databaseTarget); config.LoggingRules.Add(loggingRule); return config; }
static void Main(string[] args) { DatabaseTarget target = new DatabaseTarget(); DatabaseParameterInfo param; target.DBProvider = "mssql"; target.DBHost = "."; target.DBUserName = "******"; target.DBPassword = "******"; target.DBDatabase = "databasename"; target.CommandText = "insert into LogTable(time_stamp,level,logger,message) values(@time_stamp, @level, @logger, @message);"; param = new DatabaseParameterInfo(); param.Name = "@time_stamp"; param.Layout = "${date}"; target.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@level"; param.Layout = "${level}"; target.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@logger"; param.Layout = "${logger}"; target.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@message"; param.Layout = "${message}"; target.Parameters.Add(param); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); }
public void DatabaseExceptionTest3() { MockDbConnection.ClearLog(); var exceptions = new List<Exception>(); var db = new DatabaseTarget(); db.CommandText = "not important"; db.ConnectionString = "cannotexecute"; db.KeepConnection = true; db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; db.Initialize(null); db.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); db.Close(); Assert.Equal(3, exceptions.Count); Assert.NotNull(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.NotNull(exceptions[2]); Assert.Equal("Failure during ExecuteNonQuery", exceptions[0].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[1].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[2].Message); string expectedLog = @"Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() "; AssertLog(expectedLog); }
private DatabaseTarget GetDatabaseTarget() { var target = new DatabaseTarget { ConnectionString = "Server=localhost; Database=Hsc_DB; User Id=logDemoUser; Password=Password42", CommandText = "INSERT INTO [Hsc_DB].[dbo].[LogEntries] " + "(DateTime, Server, Application, LogLevel, Callsite, Message, EventId, Exception)" + "VALUES(GETDATE(), @server, '" + Application + "', @logLevel, @callsite, @message, @eventId, @exception);", }; target.Parameters.Add(new DatabaseParameterInfo("@server", new SimpleLayout("${machinename}"))); target.Parameters.Add(new DatabaseParameterInfo("@logLevel", new SimpleLayout("${level}"))); target.Parameters.Add(new DatabaseParameterInfo("@callsite", new SimpleLayout("${callsite}"))); target.Parameters.Add(new DatabaseParameterInfo("@message", new SimpleLayout("${message}"))); target.Parameters.Add(new DatabaseParameterInfo("@eventId", new SimpleLayout("${event-context:item=eventID}"))); target.Parameters.Add(new DatabaseParameterInfo("@exception", new SimpleLayout("${exception}"))); return target; }
public void ConnectionStringBuilderTest1() { DatabaseTarget dt; dt = new DatabaseTarget(); Assert.Equal("Server=.;Trusted_Connection=SSPI;", this.GetConnectionString(dt)); dt = new DatabaseTarget(); dt.DBHost = "${logger}"; Assert.Equal("Server=Logger1;Trusted_Connection=SSPI;", this.GetConnectionString(dt)); dt = new DatabaseTarget(); dt.DBHost = "HOST1"; dt.DBDatabase= "${logger}"; Assert.Equal("Server=HOST1;Trusted_Connection=SSPI;Database=Logger1", this.GetConnectionString(dt)); dt = new DatabaseTarget(); dt.DBHost = "HOST1"; dt.DBDatabase = "${logger}"; dt.DBUserName = "******"; dt.DBPassword = "******"; Assert.Equal("Server=HOST1;User id=user1;Password=password1;Database=Logger1", this.GetConnectionString(dt)); dt = new DatabaseTarget(); dt.ConnectionString = "customConnectionString42"; dt.DBHost = "HOST1"; dt.DBDatabase = "${logger}"; dt.DBUserName = "******"; dt.DBPassword = "******"; Assert.Equal("customConnectionString42", this.GetConnectionString(dt)); }
public void ParameterFacetTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES(@msg, @lvl, @lg)", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, Parameters = { new DatabaseParameterInfo("msg", "${message}") { Precision = 3, Scale = 7, Size = 9, }, new DatabaseParameterInfo("lvl", "${level}") { Scale = 7 }, new DatabaseParameterInfo("lg", "${logger}") { Precision = 0 }, } }; dt.Initialize(null); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); // when we pass multiple log events in an array, the target will bucket-sort them by // connection string and group all commands for the same connection string together // to minimize number of db open/close operations // in this case msg1, msg2 and msg4 will be written together to MyLogger database // and msg3 will be written to MyLogger2 database var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "msg3").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); dt.Close(); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('Server=.;Trusted_Connection=SSPI;'). CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=msg Parameter #0 Size=9 Parameter #0 Precision=3 Parameter #0 Scale=7 Parameter #0 Value=msg1 Add Parameter Parameter #0 CreateParameter(1) Parameter #1 Direction=Input Parameter #1 Name=lvl Parameter #1 Scale=7 Parameter #1 Value=Info Add Parameter Parameter #1 CreateParameter(2) Parameter #2 Direction=Input Parameter #2 Name=lg Parameter #2 Value=MyLogger Add Parameter Parameter #2 ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg) CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=msg Parameter #0 Size=9 Parameter #0 Precision=3 Parameter #0 Scale=7 Parameter #0 Value=msg3 Add Parameter Parameter #0 CreateParameter(1) Parameter #1 Direction=Input Parameter #1 Name=lvl Parameter #1 Scale=7 Parameter #1 Value=Debug Add Parameter Parameter #1 CreateParameter(2) Parameter #2 Direction=Input Parameter #2 Name=lg Parameter #2 Value=MyLogger2 Add Parameter Parameter #2 ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg) Close() Dispose() "; AssertLog(expectedLog); }
public void KeepConnectionOpenBatchedTest2() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "Database=${logger}", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, }; dt.Initialize(null); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); // when we pass multiple log events in an array, the target will bucket-sort them by // connection string and group all commands for the same connection string together // to minimize number of db open/close operations // in this case msg1, msg2 and msg4 will be written together to MyLogger database // and msg3 will be written to MyLogger2 database List<Exception> exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger2", "msg3").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg4").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('Database=MyLogger'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg4') Close() Dispose() Open('Database=MyLogger2'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') "; AssertLog(expectedLog); MockDbConnection.ClearLog(); dt.Close(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); }
public void KeepConnectionOpenBatchedTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "FooBar", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, }; dt.Initialize(null); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') "; AssertLog(expectedLog); MockDbConnection.ClearLog(); dt.Close(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); }
private DatabaseTarget ConfigureSecurityActionDatabaseTarget() { // Create database target DatabaseTarget eventLogDatabaseTarget = new DatabaseTarget(); eventLogDatabaseTarget.Name = "SecurityActionEventLogDatabase"; DatabaseParameterInfo param; string connectionString = _logWriterConfiguration.GetEventLogConnectionString(); SqlConnectionStringBuilder csBuilder = new SqlConnectionStringBuilder(connectionString); eventLogDatabaseTarget.DBProvider = "mssql"; eventLogDatabaseTarget.DBHost = csBuilder.DataSource; if (!csBuilder.IntegratedSecurity) { eventLogDatabaseTarget.DBUserName = csBuilder.UserID; eventLogDatabaseTarget.DBPassword = csBuilder.Password; } eventLogDatabaseTarget.DBDatabase = csBuilder.InitialCatalog; eventLogDatabaseTarget.CommandText = "exec [LogSecurityEvent] @action, @targetAccount, @actionBy, @actionByIPAddress, @serverIPAddress, @serverName, @application, @description"; param = new DatabaseParameterInfo(); param.Name = "@action"; param.Layout = "${event-context:item=Action}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@targetAccount"; param.Layout = "${event-context:item=TargetAccount}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@actionBy"; param.Layout = "${event-context:item=ActionBy}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@actionByIPAddress"; param.Layout = "${event-context:item=ActionByIPAddress}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@serverIPAddress"; param.Layout = "${event-context:item=ServerIPAddress}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@serverName"; param.Layout = "${machinename}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@application"; param.Layout = "${event-context:item=ApplicationName}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@description"; param.Layout = "${message}"; eventLogDatabaseTarget.Parameters.Add(param); return eventLogDatabaseTarget; }
public void OdbcShorthandNotationTest() { var dt = new DatabaseTarget() { Name = "myTarget", DBProvider = "odbc", ConnectionString = "notimportant", CommandText = "notimportant", }; dt.Initialize(null); Assert.Equal(typeof(System.Data.Odbc.OdbcConnection), dt.ConnectionType); }
public void ProviderFactoryInitTest() { var dt = new DatabaseTarget(); dt.DBProvider = "MockDb"; dt.CommandText = "Notimportant"; dt.Initialize(null); Assert.Same(MockDbFactory.Instance, dt.ProviderFactory); dt.OpenConnection("myConnectionString"); Assert.Equal(1, MockDbConnection2.OpenCount); Assert.Equal("myConnectionString", MockDbConnection2.LastOpenConnectionString); }
public void ConnectionStringNameInitTest() { var dt = new DatabaseTarget { ConnectionStringName = "MyConnectionString", CommandText = "notimportant", }; Assert.Same(ConfigurationManager.ConnectionStrings, dt.ConnectionStringsSettings); dt.ConnectionStringsSettings = new ConnectionStringSettingsCollection() { new ConnectionStringSettings("MyConnectionString", "cs1", "MockDb"), }; dt.Initialize(null); Assert.Same(MockDbFactory.Instance, dt.ProviderFactory); Assert.Equal("cs1", dt.ConnectionString.Render(LogEventInfo.CreateNullEvent())); }
public static void ConfigureNLog() { try { var config = new NLog.Config.LoggingConfiguration(); var minLogLevel = LogLevel.FromString(Environment.GetEnvironmentVariable("LOGGING_MIN_LEVEL")); var maxLogLevel = LogLevel.FromString(Environment.GetEnvironmentVariable("LOGGING_MAX_LEVEL")); //console logging var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(minLogLevel, maxLogLevel, logconsole); if (Globals.EnableFileLogging) { // file loggin var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "logfile.log" }; config.AddRule(minLogLevel, maxLogLevel, logfile); } if (Globals.EnableDBLogging) { //db loggin var logdb = new NLog.Targets.DatabaseTarget("logdb"); logdb.CommandText = @" insert into [Log] (MachineName, Logged, Level, Message,Logger, Properties, Callsite, Exception) values (@MachineName, @Logged, @Level, @Message, @Logger, @Properties, @Callsite, @Exception);"; logdb.CommandType = System.Data.CommandType.Text; logdb.ConnectionString = Globals.SkillbaseConnectionString; logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@MachineName", Layout = "${machinename}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Logged", Layout = "${date}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Level", Layout = "${level}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Message", Layout = "${message}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Logger", Layout = "${logger}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Properties", Layout = "${all-event-properties:separator=|}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Callsite", Layout = "${callsite}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Exception", Layout = "${exception:tostring}" }); config.AddRule(minLogLevel, maxLogLevel, logdb); } // Apply config NLog.LogManager.Configuration = config; } catch (Exception) { } }
public void DontRequireProviderNameInAppConfig() { LogManager.ThrowExceptions = true; var databaseTarget = new DatabaseTarget() { Name = "myTarget", ConnectionStringName = "test_connectionstring_without_providerName", CommandText = "notimportant", DBProvider = "System.Data.SqlClient" }; databaseTarget.ConnectionStringsSettings = new ConnectionStringSettingsCollection() { new ConnectionStringSettings("test_connectionstring_without_providerName", "some connectionstring"), new ConnectionStringSettings("test_connectionstring_with_providerName", "some connectionstring", "System.Data.SqlClient"), }; databaseTarget.Initialize(null); Assert.NotNull(databaseTarget.ProviderFactory); Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), databaseTarget.ProviderFactory.GetType()); }
public void ConnectionStringNameNegativeTest() { var dt = new DatabaseTarget { ConnectionStringName = "MyConnectionString", CommandText = "notimportant", ConnectionStringsSettings = new ConnectionStringSettingsCollection(), }; try { dt.Initialize(null); Assert.True(false, "Exception expected."); } catch (NLogConfigurationException configurationException) { Assert.Equal("Connection string 'MyConnectionString' is not declared in <connectionStrings /> section.", configurationException.Message); } }
private void BuildDataBaseTarget(string loggerConnectionString) { DatabaseTarget databaseTarget = new DatabaseTarget { Name = LogServiceKey, ConnectionString = loggerConnectionString, CommandText = "insert into LogEntry ([SiteId], [CreateDate], [Origin], [LogLevel], [Message], [Exception], [StackTrace]) values (@siteId, @createDate, @origin, @logLevel, @message, @exception, @stackTrace);", DBProvider = "mssql", KeepConnection = false }; databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = "@siteId", Layout = "1" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = "@createDate", Layout = "${date}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = "@origin", Layout = "${callsite}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = "@logLevel", Layout = "${level}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = "@message", Layout = "${message}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = "@exception", Layout = "${exception:format=Message,StackTrace}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = "@stackTrace", Layout = "${stackTrace}" }); this.AddTarget(LogServiceKey, databaseTarget); }
public void SqlServerShorthandNotationTest() { foreach (string provName in new[] { "microsoft", "msde", "mssql", "sqlserver" }) { var dt = new DatabaseTarget() { Name = "myTarget", DBProvider = provName, ConnectionString = "notimportant", CommandText = "notimportant", }; dt.Initialize(null); Assert.Equal(typeof(System.Data.SqlClient.SqlConnection), dt.ConnectionType); } }
static void nlog_to_db() { ensure_db_exists(); DatabaseTarget target = new DatabaseTarget(); DatabaseParameterInfo param; // just in case issues with db. LogManager.ThrowExceptions = true; // target.DBProvider = "System.Data.SQLite"; target.DBProvider = "System.Data.SQLite.SQLiteConnection, System.Data.SQLite"; //target.ConnectionString = "Data Source=${basedir}\\Log.db3;Version=3;"; target.ConnectionString = "Data Source=Log.db3;Version=3;"; target.CommandType = CommandType.Text; target.CommandText = "insert into Log(time_stamp,level,logger,message) values(@time_stamp, @level, @logger, @message);"; param = new DatabaseParameterInfo(); param.Name = "@time_stamp"; param.Layout = "${date}"; target.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@level"; param.Layout = "${level}"; target.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@logger"; param.Layout = "${logger}"; target.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@message"; param.Layout = "${message}"; target.Parameters.Add(param); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); }
private string GetConnectionString(DatabaseTarget dt) { MockDbConnection.ClearLog(); dt.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; dt.CommandText = "NotImportant"; var exceptions = new List<Exception>(); dt.Initialize(null); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "msg1").WithContinuation(exceptions.Add)); dt.Close(); return MockDbConnection.LastConnectionString; }
private DatabaseTarget ConfigureDatabaseTarget() { // Create database target DatabaseTarget eventLogDatabaseTarget = new DatabaseTarget(); try { eventLogDatabaseTarget.Name = "EventLogDatabase"; DatabaseParameterInfo param; string connectionString = _logWriterConfiguration.GetEventLogConnectionString(); SqlConnectionStringBuilder csBuilder = new SqlConnectionStringBuilder(connectionString); eventLogDatabaseTarget.DBProvider = "mssql"; eventLogDatabaseTarget.DBHost = csBuilder.DataSource; if (!csBuilder.IntegratedSecurity) { eventLogDatabaseTarget.DBUserName = csBuilder.UserID; eventLogDatabaseTarget.DBPassword = csBuilder.Password; } eventLogDatabaseTarget.DBDatabase = csBuilder.InitialCatalog; eventLogDatabaseTarget.CommandText = "exec [InsertLog] @SeverityID, @Title, @Timestamp, @MachineName, @AppDomainName, @ProcessName, @ApplicationName, @CategoryName, @ProcessAccountName, @IdentityName, @Message, @ReferenceID, @MessageType, @AdditionalInfo1, @AdditionalInfo2, @AlertCondition"; param = new DatabaseParameterInfo(); param.Name = "@SeverityID"; param.Layout = "${event-context:item=LevelID}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@Title"; param.Layout = "${event-context:item=Title}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@Timestamp"; param.Layout = "${event-context:item=EventDateTime}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@MachineName"; param.Layout = "${machinename}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@AppDomainName"; param.Layout = "${event-context:item=AppDomainName}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@ProcessName"; param.Layout = "${processname}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@ApplicationName"; param.Layout = "${event-context:item=ApplicationName}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@CategoryName"; param.Layout = "${event-context:item=Category}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@ProcessAccountName"; param.Layout = "${windows-identity}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@IdentityName"; param.Layout = "${event-context:item=Identity}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@Message"; param.Layout = "${message:withException=true}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@ReferenceID"; param.Layout = "${event-context:item=ReferenceID}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@MessageType"; param.Layout = "${event-context:item=MessageType}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@AdditionalInfo1"; param.Layout = "${event-context:item=AdditionalInfo1}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@AdditionalInfo2"; param.Layout = "${event-context:item=AdditionalInfo2}"; eventLogDatabaseTarget.Parameters.Add(param); param = new DatabaseParameterInfo(); param.Name = "@AlertCondition"; param.Layout = "${event-context:item=AlertCondition}"; eventLogDatabaseTarget.Parameters.Add(param); } catch (Exception ex) { InternalLogger.Error("*** " + ex.ToString()); throw; } return eventLogDatabaseTarget; }