簡體   English   中英

WCF服務-記錄呼叫者詳細信息

[英]WCF Service - Logging Caller Details

我創建了Windows服務(.Net 4.0),該服務通過TCP綁定公開WCF服務端點。

調用服務方法時,它將在單獨的線程中執行多個任務。 每個執行動作的類都有一個Log4Net ILog實現注入(使用依賴項注入)。

我想做的是每個日志條目都具有呼叫者的IP地址,以便我可以跟蹤呼叫或確定服務器上哪個呼叫出錯。

使用log4Net的LogicalThreadContext,我設法對寫在同一線程上的任何日志消息實現了這一點,但對其他線程上的任何消息都沒有實現。

下面的示例代碼。

服務接口:

    [ServiceContract(Namespace = "http://tremac")]
    public interface IBroadcastService
    {
        [OperationContract]
        void PublishMessage(Message message);
    }

服務實施:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
class BroadcastService: IBroadcastService
{
    private readonly ILog _logger;


    public BroadcastService(ILog logger)
    {
        _logger = logger;
        _logger.Debug("Broadcast Service Initiated");
    }

    public void PublishMessage(Message message)
    {


        var prop =
                OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as
                    RemoteEndpointMessageProperty;
        string ip = prop == null ? "" : prop.Address;

        log4net.LogicalThreadContext.Properties["CallerIp"] = ip;

        try
        {

            _logger.Info("Publishing message from " + message.Sender);
            var sinks = ObjectFactory.GetAllInstances<IMessageWriteRepository>();
            Parallel.ForEach(sinks, x => x.SaveMessage(message));
            _logger.Info("Message published");
        }
        catch (Exception ex)
        {
            _logger.Error("Issue publishing message from " + message.Sender + " on " + ip, ex);
            throw new FaultException("Message was either not published or only partially published. Please contact support");
        }
    }

}

注意在並行使用IMessageWriteRepository的幾種實現的情況下使用Parallel.Foreach。 每個實現又通過依賴注入注入了一個ILog。 似乎在這一點上,調用者的上下文已丟失。

我的Log4Net附加程序中的模式布局如下所示:

    <conversionPattern value="%date [%-5level] [%thread] [%class] [%property{CallerIp}] %message%newline" />

最后,生成的日志如下所示:

    2015-06-23 09:49:11,004 [INFO ] [13] [BroadcastService] [127.0.0.1] Publishing message from Graeme on 127.0.0.1
    2015-06-23 09:49:11,073 [INFO ] [13] [RabbitMqMessageWriter] [(null)] Sending message on topic TestTopic
    2015-06-23 09:49:11,073 [INFO ] [15] [DatabaseAndFileshareWriteMessageRepository] [(null)] Saving message body to disk
    2015-06-23 09:49:11,104 [INFO ] [15] [DatabaseAndFileshareWriteMessageRepository] [(null)] Saving message meta to database
    2015-06-23 09:49:11,737 [INFO ] [13] [BroadcastService] [127.0.0.1] Message published

請注意[(null)],其中調用者IP應該在不同線程的日志消息中。

任何建議歡迎。

感謝log4net LogicalThreadContext無法正常工作

升級到log4net版本1.12.13.0后,以下代碼將在所有線程上工作

log4net.LogicalThreadContext.Properties["CallerIp"] = ip;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM