Подтвердить что ты не робот

Как войти в UTF-8 с помощью EnterpriseLibrary.Logging

Я как бы застрял в своих поисках относительно EnterpriseLibrary.Logging. У меня есть слушатель и форматирование, настроенные следующим образом:

<add name="NormalLogListener"
     type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging"
     listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging"
     fileName="logs/MVC22.log" 
     footer="" 
     formatter="ShortLogFormatter" 
     header="" 
     rollInterval="Day" 
     timeStampPattern="yyyy-MM-dd" 
     maxArchivedFiles="14" />

...

<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging" 
     template="{timestamp(local)} - {severity} - {category} - {message}"
     name="ShortLogFormatter" />

Я использую это в нескольких проектах, и он работает нормально.

За исключением одного, я хочу, чтобы EnterpriseLibrary создавал мой файл журнала с кодировкой UTF-8 (я получаю файлы ANSI по умолчанию), но, к сожалению, я не знаю, как это сделать.

У меня есть специальные символы в строках, которые я хочу записать в свой файл (например, умляуты); Я вижу, что ведение журнала работает отлично, когда я конвертирую свой файл в UTF-8 и позволяю ему использовать его дальше, но я действительно хочу, чтобы он был создан таким образом.

Можно ли это сделать в xml-конфигурации или где-то еще?

Спасибо за любую помощь заранее!

4b9b3361

Ответ 1

Из коробки я не считаю, что блок приложения EnterpriseLibrary.Logging поддерживает вывод в utf-8. Похоже, что он выводит только ANSI по умолчанию. При этом вы всегда можете написать собственный TraceListener, который будет выводиться на utf-8.

Неподтвержденный код. Я написал это быстро и грязно. Посмотрите путь к жестко закодированным файлам:

using System;
using System.Text;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace YourNamespace
{
    [ConfigurationElementType(typeof(CustomTraceListenerData))]
    class UTF8Logging:CustomTraceListener
    {
        public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
        {
            if (data is LogEntry && this.Formatter != null)
            {
                this.WriteLine(this.Formatter.Format(data as LogEntry));
            }
            else
            {
                this.WriteLine(data.ToString());
            }
        }

        public override void Write(string message)
        {
            this.WriteLine(message);
        }

        public override void WriteLine(string message)
        {
            string fileName = @"C:\Your.log";
            using (StreamWriter sw = new StreamWriter(File.Exists(fileName) ? System.IO.File.Open(fileName, FileMode.Append) : System.IO.File.Create(fileName), Encoding.UTF8))
            {
                Byte[] logMessage = new UTF8Encoding(true).GetBytes(message);
                sw.Write(logMessage,0,logMessage.Length);
            }
        }
    }
}