本文整理汇总了C#中log4net.Core.LoggingEvent类的典型用法代码示例。如果您正苦于以下问题:C# LoggingEvent类的具体用法?C# LoggingEvent怎么用?C# LoggingEvent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
LoggingEvent类属于log4net.Core命名空间,在下文中一共展示了LoggingEvent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: WriteLog
public void WriteLog(ICorrelation correlation, LogEventLevel eventLevel, Exception exception, string formatMessage, params object[] args)
{
if (log == null)
{
log = loggerRepository.GetLogger(sourceType);
}
if (eventLevel == LogEventLevel.Verbose && !log.IsDebugEnabled)
{
return;
}
if (args != null && args.Length != 0)
{
formatMessage = string.Format(formatMessage, args);
}
log4net.Core.ILogger logger = log.Logger;
LoggingEvent logEvent = new LoggingEvent(sourceType, logger.Repository, logger.Name, MapEventLevel(eventLevel), formatMessage, exception);
if (correlation != null)
{
logEvent.Properties["CallerId"] = correlation.CallerId;
logEvent.Properties["CorrelationId"] = correlation.CorrelationId;
}
logger.Log(logEvent);
}
示例2: Append
override protected void Append(LoggingEvent loggingEvent)
{
if (m_queue == null)
{
if (MessageQueue.Exists(m_queueName))
{
m_queue = new MessageQueue(m_queueName);
}
else
{
ErrorHandler.Error("Queue ["+m_queueName+"] not found");
}
}
if (m_queue != null)
{
Message message = new Message();
message.Label = RenderLabel(loggingEvent);
using(System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, new System.Text.UTF8Encoding(false, true));
base.RenderLoggingEvent(writer, loggingEvent);
writer.Flush();
stream.Position = 0;
message.BodyStream = stream;
m_queue.Send(message);
}
}
}
示例3: Append
protected override void Append(LoggingEvent loggingEvent)
{
Level level = loggingEvent.Level;
string message = RenderLoggingEvent(loggingEvent);
if (level >= Level.Fatal)
{
Trace.Write(message, "Critical");
}
else if (level >= Level.Error)
{
Trace.TraceError(message);
}
else if (level >= Level.Warn)
{
Trace.TraceWarning(message);
}
else if (level >= Level.Info)
{
Trace.TraceInformation(message);
}
else
{
Trace.Write(message);
}
if (ImmediateFlush)
{
Trace.Flush();
}
}
示例4: SendBuffer
protected override void SendBuffer(LoggingEvent[] events)
{
BeginAsyncSend();
if (TryAsyncSend(events)) return;
EndAsyncSend();
HandleError("Failed to async send logging events in SendBuffer");
}
示例5: Append
protected override void Append(LoggingEvent le)
{
if (m_console != null)
m_console.LockOutput();
string loggingMessage = RenderLoggingEvent(le);
try
{
if (m_console != null)
{
m_console.Output(loggingMessage, le.Level);
}
else
{
if (!loggingMessage.EndsWith("\n"))
System.Console.WriteLine(loggingMessage);
else
System.Console.Write(loggingMessage);
}
}
catch (Exception e)
{
System.Console.WriteLine("Couldn't write out log message: {0}", e);
}
finally
{
if (m_console != null)
m_console.UnlockOutput();
}
}
示例6: Convert
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
{
var text = GetFullyQualifiedName(loggingEvent);
if (m_precision == 0 || text == null || text.Length < 2)
{
writer.Write(text);
return;
}
var elements = text
.Trim()
.Trim(new[] { '.' })
.Split(new[] { '.' });
if (m_precision > 0)
{
writer.Write(
string.Join("/",
elements
.Reverse()
.Take(m_precision)
.Reverse()
)
);
return;
}
writer.Write(
string.Join("/",
elements
.Take(elements.Count() + m_precision)
)
);
}
示例7: ConvertTestWithExceptionObject
public void ConvertTestWithExceptionObject()
{
var level = Level.Debug;
var writer = new StreamWriter(new MemoryStream());
var converter = new StructuredDataConverter();
Exception exception = null;
try
{
throw new Exception("test exception message");
}
catch (Exception ex)
{
exception = ex;
}
ILoggerRepository logRepository = Substitute.For<ILoggerRepository>();
var evt = new LoggingEvent(typeof(StructuredDataConverterTests), logRepository, "test logger", level, "test message", exception);
evt.Properties["log4net:StructuredDataPrefix"] = "[email protected]";
evt.Properties["log4net:syslog-exception-log"] = "file://some-log-file/who/cares";
converter.Format(writer, evt);
writer.Flush();
var result = TestUtilities.GetStringFromStream(writer.BaseStream);
Assert.IsTrue(Regex.IsMatch(result, "\\[[email protected] EventSeverity=\"DEBUG\" ExceptionSource=\"syslog4net\\.Tests\" ExceptionType=\"System\\.Exception\" ExceptionMessage=\"test exception message\" ExceptionMethodName=\"Void syslog4net\\.Tests\\.Converters\\.StructuredDataConverterTests\\.ConvertTestWithExceptionObject\\(\\)\" ExceptionFileName=\".*?StructuredDataConverterTests\\.cs\" ExceptionLineNumber=\"\\d+\" EventLog=\"file://some-log-file/who/cares\"\\]"));
}
示例8: AddProperties
private void AddProperties(object logSource, Exception exception, LoggingEvent loggingEvent)
{
loggingEvent.Properties["UserName"] = GetUserName();
try
{
ContextProperties contextProperties = _contextService.GetContextProperties();
if (contextProperties != null)
{
try
{
loggingEvent.Properties["UserAgent"] = contextProperties.UserAgent;
loggingEvent.Properties["RemoteHost"] = contextProperties.RemoteHost;
loggingEvent.Properties["Path"] = contextProperties.Path;
loggingEvent.Properties["Query"] = contextProperties.Query;
loggingEvent.Properties["RefererUrl"] = contextProperties.Referrer;
loggingEvent.Properties["RequestId"] = contextProperties.RequestId;
loggingEvent.Properties["SessionId"] = contextProperties.SessionId;
}
catch (Exception)
{
}
}
loggingEvent.Properties["ExceptionType"] = exception == null ? "" : exception.GetType().ToString();
loggingEvent.Properties["ExceptionMessage"] = exception == null ? "" : exception.Message;
loggingEvent.Properties["ExceptionStackTrace"] = exception == null ? "" : exception.StackTrace;
loggingEvent.Properties["LogSource"] = logSource.GetType().ToString();
}
catch (Exception ex)
{
var type = typeof(Log4NetLoggingService);
var logger = LogManager.GetLogger(type);
logger.Logger.Log(type, Level.Fatal, "Exception when extracting properties: " + ex.Message, ex);
}
}
示例9: AppendLoopOnAppenders
/// <summary>
/// Append on on all attached appenders.
/// </summary>
/// <param name="loggingEvent">The event being logged.</param>
/// <returns>The number of appenders called.</returns>
/// <remarks>
/// <para>
/// Calls the <see cref="IAppender.DoAppend" /> method on all
/// attached appenders.
/// </para>
/// </remarks>
public int AppendLoopOnAppenders(LoggingEvent loggingEvent)
{
if (loggingEvent == null)
{
throw new ArgumentNullException("loggingEvent");
}
// m_appenderList is null when empty
if (m_appenderList == null)
{
return 0;
}
if (m_appenderArray == null)
{
m_appenderArray = m_appenderList.ToArray();
}
foreach(IAppender appender in m_appenderArray)
{
try
{
appender.DoAppend(loggingEvent);
}
catch(Exception ex)
{
LogLog.Error("AppenderAttachedImpl: Failed to append to appender [" + appender.Name + "]", ex);
}
}
return m_appenderList.Count;
}
示例10: Append
protected override void Append(LoggingEvent loggingEvent)
{
if (FilterEvent(loggingEvent))
{
_pendingTasks.Enqueue(loggingEvent);
}
}
示例11: Append
protected override void Append(LoggingEvent loggingEvent)
{
try
{
Log _log = new Log();
string message = RenderLoggingEvent(loggingEvent);
string maquina = Dns.GetHostName();
IPAddress[] ip = Dns.GetHostAddresses(maquina);
_log.IdCorrelacao = LogicalThreadContext.Properties["CorrelationId"].ToString();
_log.DataHora = DateTime.Now;
_log.Ip = ip[1].ToString();
_log.Maquina = maquina;
_log.Usuario = loggingEvent.Identity;
_log.SistemaOrigem = _sourcesystem;
_log.Tipo = loggingEvent.Level.Name;
_log.Dados = message;
//Salva Fila Assincrono
if (_salvar == null)
{
_salvar = new SaveAsynchronous(ConsumeAsynchronous, "ThreadLog", System.Threading.ThreadPriority.Normal, true);
}
_salvar.Save(_log);
}
catch (Exception ex)
{
//TODO: Erro na gravacao da fila???
}
}
示例12: Format
public override void Format(TextWriter writer, LoggingEvent loggingEvent) {
// check arguments
if (loggingEvent == null) return;
if (loggingEvent.MessageObject == null && loggingEvent.RenderedMessage == null) return;
// get logger id
string loggerId = loggingEvent.GetLoggingEventProperty("__objectId");
// prepare stuff
string message = loggingEvent.MessageObject == null ? loggingEvent.RenderedMessage : loggingEvent.MessageObject.ToString();
string info = loggingEvent.GetLoggingEventProperty("__extendedInfo");
if (info != null) {
message = message + " " + info;
}
string[] lines = message.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
string header = string.Format("{0} [{1}] ({3}|{4}|{5}) {2} : ", loggingEvent.TimeStamp.ToString("dd-MM-yyyy hh:mm:ss,fff"), loggingEvent.Level.DisplayName.PadLeft(5, ' '), this.LoggerName(loggingEvent.LoggerName), Thread.CurrentThread.GetHashCode().ToString(CultureInfo.InvariantCulture).PadLeft(2, ' '), loggerId.PadLeft(2), Thread.CurrentPrincipal != null ? Thread.CurrentPrincipal.Identity.Name : "unknown");
const string FILLER = "\t";
for (int i = 0; i < lines.Length; i++) {
if (i == 0) {
writer.Write(header);
} else {
writer.Write(FILLER);
}
writer.WriteLine(lines[i]);
}
}
示例13: Append
override protected void Append(LoggingEvent loggingEvent)
{
object messageObject = loggingEvent.MessageObject;
if (messageObject != null && !(messageObject is string))
{
Type messageType = messageObject.GetType();
if (m_expandProperties)
{
// Get all public instance properties
foreach(PropertyInfo propertyInfo in messageType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (propertyInfo.CanRead)
{
loggingEvent.Properties[propertyInfo.Name] = propertyInfo.GetValue(messageObject, null);
}
}
}
if (m_expandFields)
{
// Get all public instance fields
foreach(FieldInfo fieldInfo in messageType.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
loggingEvent.Properties[fieldInfo.Name] = fieldInfo.GetValue(messageObject);
}
}
}
// Delegate to base class which will forward
base.Append(loggingEvent);
}
示例14: Format
public override void Format(TextWriter textWriter, LoggingEvent loggingEvent)
{
base.Format(textWriter, loggingEvent);
if (loggingEvent.ExceptionObject != null)
textWriter.Write(Environment.StackTrace);
}
示例15: Convert
/// <summary>
/// Convert the pattern to the rendered message
/// </summary>
/// <param name="writer"><see cref="T:System.IO.TextWriter" /> that will receive the formatted result.</param>
/// <param name="loggingEvent">the event being logged</param>
/// <remarks>
/// Render the <see cref="M:log4net.Layout.Pattern.NamedPatternConverter.GetFullyQualifiedName(log4net.Core.LoggingEvent)" /> to the precision
/// specified by the <see cref="P:log4net.Util.PatternConverter.Option" /> property.
/// </remarks>
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
{
string text = this.GetFullyQualifiedName(loggingEvent);
if (this.m_precision <= 0 || text == null || text.Length < 2)
{
writer.Write(text);
}
else
{
int num = text.Length;
string str = string.Empty;
if (text.EndsWith("."))
{
str = ".";
text = text.Substring(0, num - 1);
num--;
}
int num2 = text.LastIndexOf(".");
int num3 = 1;
while (num2 > 0 && num3 < this.m_precision)
{
num2 = text.LastIndexOf('.', num2 - 1);
num3++;
}
if (num2 == -1)
{
writer.Write(text + str);
}
else
{
writer.Write(text.Substring(num2 + 1, num - num2 - 1) + str);
}
}
}