当前位置: 首页>>代码示例>>C#>>正文


C# Targets.DatabaseTarget类代码示例

本文整理汇总了C#中NLog.Targets.DatabaseTarget的典型用法代码示例。如果您正苦于以下问题:C# DatabaseTarget类的具体用法?C# DatabaseTarget怎么用?C# DatabaseTarget使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


DatabaseTarget类属于NLog.Targets命名空间,在下文中一共展示了DatabaseTarget类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SimpleDatabaseTest

        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);
        }
开发者ID:304NotModified,项目名称:NLog-1,代码行数:35,代码来源:DatabaseTargetTests.cs

示例2: Main

    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");
    }
开发者ID:CharlieBP,项目名称:NLog,代码行数:20,代码来源:Example.cs

示例3: Main

    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");
    }
开发者ID:ExM,项目名称:NLog,代码行数:21,代码来源:Example.cs

示例4: Create

        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;
        }
开发者ID:yuki87,项目名称:Hinata-on-premise,代码行数:37,代码来源:TraceLogConfigurationFactory.cs

示例5: ConnectionStringBuilderTest1

        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 = "user1";
            dt.DBPassword = "password1";
            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 = "user1";
            dt.DBPassword = "password1";
            Assert.Equal("customConnectionString42", this.GetConnectionString(dt));
        }
开发者ID:xiaopohou,项目名称:NLog,代码行数:31,代码来源:DatabaseTargetTests.cs

示例6: ParameterFacetTest

        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);
        }
开发者ID:xiaopohou,项目名称:NLog,代码行数:97,代码来源:DatabaseTargetTests.cs

示例7: KeepConnectionOpenBatchedTest2

        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);
        }
开发者ID:xiaopohou,项目名称:NLog,代码行数:56,代码来源:DatabaseTargetTests.cs

示例8: ConfigureSecurityActionDatabaseTarget

        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;
        }
开发者ID:BogamSushil,项目名称:OnlineGrocery,代码行数:65,代码来源:NLogLogWriter.cs

示例9: OdbcShorthandNotationTest

        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);
        }
开发者ID:xiaopohou,项目名称:NLog,代码行数:13,代码来源:DatabaseTargetTests.cs

示例10: ProviderFactoryInitTest

 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);
 }
开发者ID:xiaopohou,项目名称:NLog,代码行数:11,代码来源:DatabaseTargetTests.cs

示例11: ConnectionStringNameInitTest

        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()));
        }
开发者ID:xiaopohou,项目名称:NLog,代码行数:18,代码来源:DatabaseTargetTests.cs

示例12: DontRequireProviderNameInAppConfig

        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());
        }
开发者ID:NLog,项目名称:NLog,代码行数:22,代码来源:DatabaseTargetTests.cs

示例13: GetDatabaseTarget

        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;
        }
开发者ID:Hoejsgaard,项目名称:Hsc.Core,代码行数:18,代码来源:MockNlogConfigurationRepository.cs

示例14: DatabaseExceptionTest1

        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);
        }
开发者ID:xiaopohou,项目名称:NLog,代码行数:18,代码来源:DatabaseTargetTests.cs

示例15: DatabaseExceptionTest3

        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);
        }
开发者ID:xiaopohou,项目名称:NLog,代码行数:40,代码来源:DatabaseTargetTests.cs


注:本文中的NLog.Targets.DatabaseTarget类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。