如何使用Rabbit-mq客户端设置日志记录到本地硬盘?

时间:2018-07-03 20:28:51

标签: c# logging rabbitmq

是否可以通过编程方式 打开登录到本地硬盘驱动器?

(例如:登录到文件C:\ temp \ Rabbit.log)

((当然,目录和名称也会改变)

换句话说,我希望能够在创建Rabbit MQ连接时打开(或关闭)登录记录。

背景: 从我的应用程序中的引用中使用RabbitMQ

在Visual Studio中,通过NuGet右键单击“参考”

add reference : RabbitMQ.Client.dll (v4.0.30319)

这是我的代码,它运行Rabbit MQ的客户端。 (消息处理代码已被删除)

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.MessagePatterns;

private void Internal_Run(CancellationToken cancelToken)
{
    var connectionFactory = new ConnectionFactory();

    // I know this is wrong... but this is what I would ***like*** to do:
    // connectionFactory.IsLogging = true;
    // connectionFactory.LogPathAndFile = "C:\\Temp\\Rabbit.log";


    connectionFactory.HostName = "My Host";
    connectionFactory.UserName = "My userName";
    connectionFactory.Password = "My password";
    string QueueName = "My unique queue name";

    try
    {
        using (IConnection connection = connectionFactory.CreateConnection())
        {
            using (IModel model = connection.CreateModel())
            {
                //Note declare the queue here, as well. Because we might start the receiver before the sender, 
                // we want to make sure the queue exists before we try to consume messages from it
                model.QueueDeclare(queue: QueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
                var subscription = new Subscription(model, QueueName, false);

                int milisecondTimeOut_RabbitMQ = 500;
                while (true)
                {
                    BasicDeliverEventArgs basicDeliveryEventArgs;
                    if (subscription.Next(milisecondTimeOut_RabbitMQ, out basicDeliveryEventArgs))
                    {
                        if (basicDeliveryEventArgs == null)
                        {
                            continue;
                        }
                        if (basicDeliveryEventArgs.Body.Length == 0)
                        {
                            continue;
                        }

                        string messageContent = Encoding.UTF8.GetString(basicDeliveryEventArgs.Body);

                        subscription.Ack(basicDeliveryEventArgs);  // send the ACK back to queue to let Rabbit know I processed the message
                    }

                    if (cancelToken.IsCancellationRequested)
                    {
                        break;
                    }
                }
            }
        }
    }
    catch (OperationCanceledException oce)
    {
        // this is an expected cancellation - program shutting down
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

1 个答案:

答案 0 :(得分:0)

必须创建自定义NLOG配置文件。这是一个示例:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  autoReload="true"
  throwExceptions="false">

<variable name="AppName" value="ManagerService" />
<variable name="LogDir" value="Logs" />

<variable name="logFormat_File" value="[${longdate}][${logger}] 
[${message}${onexception:${newline}EXCEPTION\: ${exception:format=ToString}}]"/>
<variable name="logFormat_Console" value="${longdate} | ${logger} | 
${level:uppercase=true} | ${message}"/>
<variable name="logFormat_Debugger" value="[${logger}] '${message}'"/>

<targets async="true">

<target xsi:type="File"
        name="Log_Main"
        layout="${logFormat_File}"
        fileName="${basedir}${LogDir}\Main.log"
        keepFileOpen="false"
        archiveFileName="${basedir}${LogDir}\Main_${shortdate}.{##}.bak"
        archiveNumbering="Sequence"
        archiveEvery="Day"
        maxArchiveFiles="30"
        />

    <target xsi:type="File"
        name="Log_Timing"
        layout="${logFormat_File}"
        fileName="${basedir}${LogDir}\Timing.log"
        keepFileOpen="false"
        archiveFileName="${basedir}${LogDir}\Timing_${shortdate}.{##}.bak"
        archiveNumbering="Sequence"
        archiveEvery="Day"
        maxArchiveFiles="30"
        />

        <target xsi:type="File"
        name="Log_Trans"
        layout="${logFormat_File}"
        fileName="${basedir}${LogDir}\Trans.log"
        keepFileOpen="false"
        archiveFileName="${basedir}${LogDir}\Trans_${shortdate}.{##}.bak"
        archiveNumbering="Sequence"
        archiveEvery="Day"
        maxArchiveFiles="30"
        />


        <target xsi:type="File"
        name="Error_Log"
        layout="${logFormat_File}"
        fileName="${basedir}${LogDir}\Error.log"
        keepFileOpen="false"
        archiveFileName="${basedir}${LogDir}\Error_${shortdate}.{##}.bak"
        archiveNumbering="Sequence"
        archiveEvery="Day"
        maxArchiveFiles="30"
        />

        <target xsi:type="File"
        name="Warn_Log"
        layout="${logFormat_File}"
        fileName="${basedir}${LogDir}\Warn.log"
        keepFileOpen="false"
        archiveFileName="${basedir}${LogDir}\Warn_${shortdate}.{##}.bak"
        archiveNumbering="Sequence"
        archiveEvery="Day"
        maxArchiveFiles="30"
        />

        <target xsi:type="File"
        name="DB_Log"
        layout="${logFormat_File}"
        fileName="${basedir}${LogDir}\DB.log"
        keepFileOpen="false"
        archiveFileName="${basedir}${LogDir}\DB_${shortdate}.{##}.bak"
        archiveNumbering="Sequence"
        archiveEvery="Day"
        maxArchiveFiles="30"
        />

        <target xsi:type="File"
        name="MQ_Log"
        layout="${logFormat_File}"
        fileName="${basedir}${LogDir}\MQ.log"
        keepFileOpen="false"
        archiveFileName="${basedir}${LogDir}\MQ_${shortdate}.{##}.bak"
        archiveNumbering="Sequence"
        archiveEvery="Day"
        maxArchiveFiles="30"
        />

        <target xsi:type="File"
        name="Rest_Log"
        layout="${logFormat_File}"
        fileName="${basedir}${LogDir}\Rest.log"
        keepFileOpen="false"
        archiveFileName="${basedir}${LogDir}\Rest_${shortdate}.{##}.bak"
        archiveNumbering="Sequence"
        archiveEvery="Day"
        maxArchiveFiles="30"
        />

        <target xsi:type="File"
        name="BM_Log"
        layout="${logFormat_File}"
        fileName="${basedir}${LogDir}\BM.log"
        keepFileOpen="false"
        archiveFileName="${basedir}${LogDir}\BM_${shortdate}.{##}.bak"
        archiveNumbering="Sequence"
        archiveEvery="Day"
        maxArchiveFiles="30"
        />


<target xsi:type="EventLog"
        name="eventlog"
        source="CetrusManagerService"
        log="Cetrus"
        layout="${message}${newline}${exception:format=ToString}"/>

<target name="debugger" xsi:type="Debugger" layout="${logFormat_Debugger}"/>

<target name="console" xsi:type="Console" layout="${logFormat_Console}" />

</targets>


<rules>
<logger name="Manager.Calls.Manager" writeTo="Log_Main" level="Info" />

<logger name="Manager.Calls.Rest" writeTo="Rest_Log" levels="Info,Error" />

<logger name="Manager.Timing.*" writeTo="Log_Timing" level="Info" />

<logger name="Manager.TransactionProcessor.*" writeTo="Log_Trans" levels="Info,Warn,Error" />

<logger name="Manager.Calls.DB" writeTo="DB_Log" levels="Info,Error" />

<logger name="Manager.Calls.MessageQueue" writeTo="MQ_Log" level="Info" />

<logger name="Manager.Calls.BinaryManager" writeTo="BM_Log" level="Info" />

<logger name="*" writeTo="Error_Log" level="Error" />

<logger name="*" writeTo="Warn_Log" level="Warn" />

<logger name="*" writeTo="eventlog" minlevel="Error" />

<logger name="*" writeTo="debugger" minlevel="Trace" />

<logger name="*" writeTo="console" minlevel="Info" />

</rules>

</nlog>