本文整理汇总了C#中log4net.ILog.ErrorFormat方法的典型用法代码示例。如果您正苦于以下问题:C# ILog.ErrorFormat方法的具体用法?C# ILog.ErrorFormat怎么用?C# ILog.ErrorFormat使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类log4net.ILog
的用法示例。
在下文中一共展示了ILog.ErrorFormat方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LogSqlException
public static void LogSqlException(SqlException ex, ILog log)
{
log.ErrorFormat("Server: {0}, Procedure:{1} Number:{2} Message:{3}", ex.Server, ex.Procedure, ex.Number, ex.Message);
foreach (SqlError item in ex.Errors)
{
log.ErrorFormat("State: {0}, Procedure: {1}, Number: {2}, LineNumber: {3}, Message:{4}", item.State, item.Procedure, item.Number, item.LineNumber, item.Message);
}
}
示例2: Init
public static void Init()
{
_log = LogManager.GetLogger("AppDomain");
var _fa =
new FileAppender()
{
Layout = new log4net.Layout.PatternLayout("%timestamp [%thread] %-5level %logger - %message%newline"),
File = Path.Combine(Environment.CurrentDirectory, "update.log"),
AppendToFile = false
};
_fa.ActivateOptions();
BasicConfigurator.Configure(
_fa,
new ConsoleAppender()
);
AppDomain.CurrentDomain.AssemblyLoad += (sender, e) =>
{
_log.DebugFormat("Assembly load: {0}", e.LoadedAssembly.FullName);
};
AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
{
_log.Info("Process exiting.");
};
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
_log.ErrorFormat("Unhandled exception: {0}", e.ExceptionObject.ToString());
};
}
示例3: Error
public static void Error(ILog log, string format, params object[] @params)
{
if (log == null)
{
return;
}
log.ErrorFormat(format, @params);
}
示例4: ToLog
public virtual void ToLog(ILog log)
{
// Remove password from logging
var safeConnectionString = new SqlConnectionStringBuilder(ConnectionString);
if (!string.IsNullOrEmpty(safeConnectionString.Password))
{
safeConnectionString.Password = "[redacted]";
}
log.InfoFormat(" {0}: {1}", Name, safeConnectionString);
// Validate that connection string do not provide both Trusted Security AND user/password
bool hasUserCreds = !string.IsNullOrEmpty(safeConnectionString.UserID) || !string.IsNullOrEmpty(safeConnectionString.Password);
if (safeConnectionString.IntegratedSecurity == hasUserCreds)
{
log.Error("==================================================");
log.ErrorFormat("Connection string for '{0}' may not contain both Integrated Security and User ID/Password credentials. " +
"Review the readme.md and update the config file.",
safeConnectionString.DataSource);
log.Error("==================================================");
}
}
示例5: RunService
private static void RunService(CommandLineParser parser, Action<StringDictionary> environment, ILog logger)
{
var service = new ServiceController(parser.Target);
if (service.Status != ServiceControllerStatus.Stopped)
{
logger.ErrorFormat("The service '{0}' is already running. The profiler cannot attach to an already running service.",
parser.Target);
return;
}
// now to set the environment variables
var profilerEnvironment = new StringDictionary();
environment(profilerEnvironment);
var serviceEnvironment = new ServiceEnvironmentManagement();
try
{
serviceEnvironment.PrepareServiceEnvironment(parser.Target,
(from string key in profilerEnvironment.Keys select string.Format("{0}={1}", key, profilerEnvironment[key])).ToArray());
// now start the service
service = new ServiceController(parser.Target);
service.Start();
logger.InfoFormat("Service starting '{0}'", parser.Target);
service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));
logger.InfoFormat("Service started '{0}'", parser.Target);
}
finally
{
// once the serice has started set the environment variables back - just in case
serviceEnvironment.ResetServiceEnvironment();
}
// and wait for it to stop
service.WaitForStatus(ServiceControllerStatus.Stopped);
logger.InfoFormat("Service stopped '{0}'", parser.Target);
}
示例6: ToLog
public override void ToLog(ILog log)
{
base.ToLog(log);
// Attempt to connect to the server and get basic details about the server and the databases.
Dictionary<string, DatabaseDetails> databaseDetailsByName;
try
{
var queryLocator = new QueryLocator(new DapperWrapper());
SqlQuery serverDetailsQuery = queryLocator.PrepareQueries(new[] {typeof (SqlServerDetails),}, false).Single();
SqlQuery databasesDetailsQuery = queryLocator.PrepareQueries(new[] {typeof (DatabaseDetails),}, false).Single();
using (var conn = new SqlConnection(ConnectionString))
{
// Log the server details
SqlServerDetails serverDetails = serverDetailsQuery.Query<SqlServerDetails>(conn, this).Single();
LogVerboseSqlResults(serverDetailsQuery, new[] {serverDetails});
log.InfoFormat(" {0} {1} {2} ({3})", serverDetails.SQLTitle, serverDetails.Edition, serverDetails.ProductLevel, serverDetails.ProductVersion);
// Sotre these for reporting below
DatabaseDetails[] databasesDetails = databasesDetailsQuery.DatabaseMetricQuery<DatabaseDetails>(conn, this).ToArray();
LogVerboseSqlResults(databasesDetailsQuery, databasesDetails);
databaseDetailsByName = databasesDetails.ToDictionary(d => d.DatabaseName);
}
}
catch (Exception e)
{
// Just log some details here. The subsequent queries for metrics yields more error details.
log.ErrorFormat(" Unable to connect: {0}", e.Message);
databaseDetailsByName = null;
}
bool hasExplicitIncludedDatabases = IncludedDatabaseNames.Any();
if (hasExplicitIncludedDatabases)
{
// Show the user the databases we'll be working from
foreach (Database database in IncludedDatabases)
{
string message = " Including DB: " + database.Name;
// When the details are reachable, show them
if (databaseDetailsByName != null)
{
DatabaseDetails details;
if (databaseDetailsByName.TryGetValue(database.Name, out details))
{
message += string.Format(" [CompatibilityLevel={0};State={1}({2});CreateDate={3:yyyy-MM-dd};UserAccess={4}({5})]",
details.compatibility_level,
details.state_desc,
details.state,
details.create_date,
details.user_access_desc,
details.user_access);
}
else
{
// More error details are reported with metric queries
message += " [Unable to find database information]";
}
}
log.Info(message);
}
}
else if (databaseDetailsByName != null)
{
// The user didn't specifically include any databases
// Report details for all of the DBs we expect to gather metrics against
foreach (DatabaseDetails details in databaseDetailsByName.Values)
{
log.InfoFormat(" Including DB: {0} [CompatibilityLevel={1};State={2}({3});CreateDate={4:yyyy-MM-dd};UserAccess={5}({6})]",
details.DatabaseName,
details.compatibility_level,
details.state_desc,
details.state,
details.create_date,
details.user_access_desc,
details.user_access);
}
}
// If there are included DB's, log the Excluded DB's as DEBUG info.
Action<string> logger = hasExplicitIncludedDatabases ? (Action<string>) log.Debug : log.Info;
foreach (string database in ExcludedDatabaseNames)
{
logger(" Excluding DB: " + database);
}
}
示例7: GetWebProxy
private static IWebProxy GetWebProxy(NewRelicConfigurationSection section, ILog log)
{
var proxyElement = section.Proxy;
if (proxyElement == null || !proxyElement.ElementInformation.IsPresent) return null;
Uri uri;
if (!Uri.TryCreate(proxyElement.Host, UriKind.RelativeOrAbsolute, out uri))
{
log.ErrorFormat("Proxy host '{0}' is not a valid URI, skipping proxy.", proxyElement.Host);
return null;
}
int port;
if (!int.TryParse(proxyElement.Port, out port))
{
log.ErrorFormat("Unable to parse proxy port from '{0}', skipping proxy. Expecting a number from 1-65535.", proxyElement.Port);
return null;
}
WebProxy webProxy;
try
{
webProxy = new WebProxy(proxyElement.Host, port);
}
catch (Exception e)
{
log.ErrorFormat("Proxy settings are invalid. {0}", e.Message);
return null;
}
if ("true".Equals(proxyElement.UseDefaultCredentials, StringComparison.InvariantCultureIgnoreCase))
{
webProxy.UseDefaultCredentials = true;
webProxy.Credentials = CredentialCache.DefaultCredentials;
_ProxyDetails = string.Format("Proxy Server: {0}:{1} with default credentials", proxyElement.Host, port);
}
else if (!string.IsNullOrEmpty(proxyElement.User))
{
if (string.IsNullOrEmpty(proxyElement.Domain))
{
webProxy.Credentials = new NetworkCredential(proxyElement.User, proxyElement.Password);
_ProxyDetails = string.Format("Proxy Server: {0}@{1}:{2}", proxyElement.User, proxyElement.Host, port);
}
else
{
webProxy.Credentials = new NetworkCredential(proxyElement.User, proxyElement.Password, proxyElement.Domain);
_ProxyDetails = string.Format("Proxy Server: {0}\\{1}@{2}:{3}", proxyElement.Domain, proxyElement.User, proxyElement.Host, port);
}
}
else
{
_ProxyDetails = string.Format("Proxy Server: {0}:{1}", proxyElement.Host, port);
}
return webProxy;
}
示例8: Main
static int Main(string[] args)
{
GlobalContext.Properties["LogName"] = Path.Combine(FolderLocator.GetLocalAppDataFolder(), "Lord KiRon\\");
Log = LogManager.GetLogger(Assembly.GetExecutingAssembly().GetType());
// Log an info level message
Log.Info("FB2EPUB shell extension registration utility by Lord KiRon");
List<string> options = new List<string>();
try
{
foreach (var param in args)
{
if (IsOptionParameter(param))
{
options.Add(param);
}
}
ExtRegistrator registrator = new ExtRegistrator();
if (options.Count > 0)
{
string fileName = GetDllFileName();
if ((options[0].ToLower() == "/r") || (options[0].ToLower() == "-r"))
{
string filePath = LocationDetector.DetectLocation(fileName);
if (string.IsNullOrEmpty(filePath))
{
Log.ErrorFormat("Unable to locate {0}", fileName);
return 1;
}
registrator.RegistrationPath = filePath;
Log.InfoFormat("Registering {0}",filePath);
registrator.Register(ExtRegistrator.RegistrationExtensionEnum.BaseSet);
return 1;
}
if ((options[0].ToLower() == "/rall") || (options[0].ToLower() == "-rall"))
{
string filePath = LocationDetector.DetectLocation(fileName);
if (string.IsNullOrEmpty(filePath))
{
Log.ErrorFormat("Unable to locate {0}", fileName);
return 1;
}
registrator.RegistrationPath = filePath;
Log.InfoFormat("Registering {0}", filePath);
registrator.Register(ExtRegistrator.RegistrationExtensionEnum.All);
return 0;
}
if ((options[0].ToLower() == "/u") || options[0].ToLower() == "-u")
{
Log.Info("Unregistering");
registrator.Unregister();
return 0;
}
}
else
{
Application.Run(new MainForm());
}
}
catch (Exception ex)
{
Log.Error(ex);
return 2;
}
return 0;
}
示例9: CheckNotNullAndLog
private void CheckNotNullAndLog(string value, string name, ILog logger)
{
if (value == null)
//logger.ErrorFormat(" {0} {1} {2} {3} is null.",
logger.ErrorFormat(MsgNull,
this.Name,
string.IsNullOrEmpty(this.Line)?string.Empty:this.Line ,
string.IsNullOrEmpty(this.Station)?string.Empty:this.Station,
name);
else if (value.Trim() == string.Empty)
//logger.ErrorFormat(" {0} {1} {2} {3} is empty.", this.Name,
logger.ErrorFormat(MsgEmpty, this.Name,
string.IsNullOrEmpty(this.Line) ? string.Empty : this.Line,
string.IsNullOrEmpty(this.Station) ? string.Empty : this.Station,
name);
}
示例10: RunService
private static void RunService(CommandLineParser parser, Action<StringDictionary> environment, ILog logger)
{
if (ServiceEnvironmentManagementEx.IsServiceDisabled(parser.Target))
{
logger.ErrorFormat("The service '{0}' is disabled. Please enable the service.",
parser.Target);
return;
}
var service = new ServiceController(parser.Target);
try
{
if (service.Status != ServiceControllerStatus.Stopped)
{
logger.ErrorFormat(
"The service '{0}' is already running. The profiler cannot attach to an already running service.",
parser.Target);
return;
}
// now to set the environment variables
var profilerEnvironment = new StringDictionary();
environment(profilerEnvironment);
var serviceEnvironment = new ServiceEnvironmentManagement();
try
{
serviceEnvironment.PrepareServiceEnvironment(
parser.Target,
parser.ServiceEnvironment,
(from string key in profilerEnvironment.Keys
select string.Format("{0}={1}", key, profilerEnvironment[key])).ToArray());
// now start the service
var old = service;
service = new ServiceController(parser.Target);
old.Dispose();
if (parser.Target.ToLower().Equals("w3svc"))
{
// Service will not automatically start
if (! TerminateCurrentW3SvcHost(logger) ||
!ServiceEnvironmentManagementEx.IsServiceStartAutomatic(parser.Target))
{
service.Start();
}
}
else
{
service.Start();
}
logger.InfoFormat("Service starting '{0}'", parser.Target);
service.WaitForStatus(ServiceControllerStatus.Running, parser.ServiceStartTimeout);
logger.InfoFormat("Service started '{0}'", parser.Target);
}
catch (InvalidOperationException fault)
{
logger.FatalFormat("Service launch failed with '{0}'", fault);
}
finally
{
// once the serice has started set the environment variables back - just in case
serviceEnvironment.ResetServiceEnvironment();
}
// and wait for it to stop
service.WaitForStatus(ServiceControllerStatus.Stopped);
logger.InfoFormat("Service stopped '{0}'", parser.Target);
// Stopping w3svc host
if (parser.Target.ToLower().Equals("w3svc"))
{
logger.InfoFormat("Stopping svchost to clean up environment variables for w3svc", parser.Target);
if (ServiceEnvironmentManagementEx.IsServiceStartAutomatic(parser.Target))
{
logger.InfoFormat("Please note that the 'w3svc' service may automatically start");
}
TerminateCurrentW3SvcHost(logger);
}
}
finally
{
service.Dispose();
}
}
示例11: ErrorFormat
/// <summary>
/// Logs a formatted message string with the <see cref="F:log4net.Core.Level.Error"/> level.
/// </summary>
/// <param name="format">A String containing zero or more format items</param>
/// <param name="args">An Object array containing zero or more objects to format</param>
/// <param name="log">The log.</param>
/// <overloads>Log a formatted message string with the <see cref="F:log4net.Core.Level.Error"/> level.</overloads>
/// <remarks>
/// <para>
/// The message is formatted using the <c>String.Format</c> method. See
/// <see cref="M:System.String.Format(System.String,System.Object[])"/> for details of the syntax of the format string and the behavior
/// of the formatting.
/// </para>
/// <para>
/// This method does not take an <see cref="T:System.Exception"/> object to include in the
/// log event. To pass an <see cref="T:System.Exception"/> use one of the <see cref="M:log4net.ILog.Error(System.Object)"/>
/// methods instead.
/// </para>
/// </remarks>
/// <seealso cref="M:log4net.ILog.Error(System.Object,System.Exception)"/>
/// <seealso cref="P:log4net.ILog.IsErrorEnabled"/>
public static void ErrorFormat(string format, object[] args, ILog log)
{
log.ErrorFormat(CultureInfo.InvariantCulture, format, args);
}
示例12: TcpSocketListener
public TcpSocketListener(string listeningAddress, int port)
{
_logger = LogManager.GetLogger(LogDomain);
_logger.Debug(string.Format("Creating TcpSocketListener with listeningAddress={0} port={1}", listeningAddress, port));
_listeningAddress = listeningAddress;
_port = port;
if(listeningAddress == "" || listeningAddress == "0.0.0.0")
_endpoint = new IPEndPoint(IPAddress.Any, _port);
else if(listeningAddress == "::0")
_endpoint = new IPEndPoint(IPAddress.IPv6Any, _port);
else
{
IPHostEntry hostEntry = Dns.GetHostEntry(listeningAddress);
if(hostEntry == null || hostEntry.AddressList == null || hostEntry.AddressList.Length == 0)
{
_logger.ErrorFormat("Could not resolve address '{0}'", listeningAddress);
throw new ConnectionException(string.Format("Could not resolve address '{0}'", listeningAddress));
}
_endpoint = new IPEndPoint(hostEntry.AddressList[0], port);
}
}
示例13: LoggingError
public static void LoggingError(ILog logger, string format, params object[] args)
{
logger.ErrorFormat(format, args);
// logger.DebugFormat("ERROR: {0}::{1}()", method.DeclaringType, method.Name);
}
示例14: Main
private static void Main()
{
XmlConfigurator.Configure();
_log = LogManager.GetLogger(ServiceName);
_log.InfoFormat("Starting service ...");
_appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName.Replace(".vshost", string.Empty);
_displayName = _appName;
_parameters = ParseCommandLine(Environment.CommandLine);
//определяем комманду на удаление сервиса
var isNeedRemoveService = _parameters.ContainsKey(ParamServiceNo);
if (isNeedRemoveService)
{
RemoveService();
return;
}
//определяем какой вид запуска (сервис или консоль)
var runAsService = _parameters.ContainsKey(ParamService);
//запуск приложения как сервиса
if (runAsService)
{
// если сервиса нет - устанавливаем его и запускаем
var sysService = GetInstalledService();
if (sysService == null)
{
sysService = CreateService();
sysService.Start();
return;
}
// если сервис есть - запускаем логику
var svc = new SchedulerHost(new ServiceContext(_parameters));
ServiceBase.Run(svc);
}
//запуск в режиме консольного приложения
else
{
var app = new SchedulerHost(new ServiceContext(_parameters));
try
{
app.Start(null);
_log.Info("Press escape to exit");
ConsoleKeyInfo keyInfo;
do keyInfo = Console.ReadKey(); while (keyInfo.Key != ConsoleKey.Escape);
}
catch (Exception ex)
{
_log.ErrorFormat("Fatal error: {0}", ex);
Console.WriteLine("Press a key to exit");
Console.ReadKey();
}
finally
{
app.Stop();
}
}
}
示例15: LogError
/// <summary>
/// Logs the error.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="provider">The provider.</param>
/// <param name="format">The format.</param>
/// <param name="args">The args.</param>
public static void LogError( Type type, IFormatProvider provider, string format, params object[] args )
{
Log = LogManager.GetLogger ( type );
Log.ErrorFormat ( provider, format, args );
}