本文整理匯總了C#中NLog.Logger.Fatal方法的典型用法代碼示例。如果您正苦於以下問題:C# Logger.Fatal方法的具體用法?C# Logger.Fatal怎麽用?C# Logger.Fatal使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類NLog.Logger
的用法示例。
在下文中一共展示了Logger.Fatal方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Handle
public void Handle(YahooHeatData heatData, Logger logger)
{
try
{
using (var ctx = new HeatYahooContext())
{
ctx.BulkInsert(new YahooHeatData[] {heatData});
}
}
catch (DbEntityValidationException e)
{
logger.Fatal(e.Dump());
throw;
}
catch (SqlException e)
{
if (!e.Message.Contains("Cannot insert duplicate key row"))
{
logger.Fatal(e.Dump());
throw;
}
}
catch (Exception e)
{
logger.Fatal(e.Dump());
throw;
}
}
示例2: BotCredentials
public BotCredentials()
{
_log = LogManager.GetCurrentClassLogger();
try { File.WriteAllText("./credentials_example.json", JsonConvert.SerializeObject(new CredentialsModel(), Formatting.Indented)); } catch { }
if(!File.Exists(credsFileName))
_log.Warn($"credentials.json is missing. Attempting to load creds from environment variables prefixed with 'NadekoBot_'. Example is in {Path.GetFullPath("./credentials_example.json")}");
try
{
var configBuilder = new ConfigurationBuilder();
configBuilder.AddJsonFile(credsFileName, true)
.AddEnvironmentVariables("NadekoBot_");
var data = configBuilder.Build();
Token = data[nameof(Token)];
if (string.IsNullOrWhiteSpace(Token))
throw new ArgumentNullException(nameof(Token), "Token is missing from credentials.json or Environment varibles.");
OwnerIds = data.GetSection("OwnerIds").GetChildren().Select(c => ulong.Parse(c.Value)).ToArray();
LoLApiKey = data[nameof(LoLApiKey)];
GoogleApiKey = data[nameof(GoogleApiKey)];
MashapeKey = data[nameof(MashapeKey)];
OsuApiKey = data[nameof(OsuApiKey)];
int ts = 1;
int.TryParse(data[nameof(TotalShards)], out ts);
TotalShards = ts < 1 ? 1 : ts;
ulong clId = 0;
ulong.TryParse(data[nameof(ClientId)], out clId);
ClientId = clId;
SoundCloudClientId = data[nameof(SoundCloudClientId)];
CarbonKey = data[nameof(CarbonKey)];
var dbSection = data.GetSection("db");
Db = new DBConfig(string.IsNullOrWhiteSpace(dbSection["Type"])
? "sqlite"
: dbSection["Type"],
string.IsNullOrWhiteSpace(dbSection["ConnectionString"])
? "Filename=./data/NadekoBot.db"
: dbSection["ConnectionString"]);
}
catch (Exception ex)
{
_log.Fatal(ex.Message);
_log.Fatal(ex);
throw;
}
}
示例3: ProcessResults
public static void ProcessResults(JSONDiff jd, Logger l)
{
if (jd.Messages.Any())
{
l.Info("--Issues--");
jd.Messages.ForEach(s2 =>
{
var mess = s2.Message?.Trim();
var exp = s2.Exception?.Trim();
var m = $"{s2.ProblemType} | {mess} | {exp}";
m = m.Replace("\r\n", "");
switch (s2.WarnLevel)
{
case JSONWarnLevel.Warn:
l.Warn(m);
break;
case JSONWarnLevel.Error:
l.Error(m);
break;
case JSONWarnLevel.Fatal:
l.Fatal(m);
break;
default:
throw new ArgumentOutOfRangeException();
}
});
l.Info("-----------");
}
else
{
l.Info("--Success--");
l.Info("-----------");
}
}
示例4: CollectorService
public CollectorService()
{
this.ServiceName = AscMailCollectionServiceName;
this.EventLog.Log = "Application";
// These Flags set whether or not to handle that specific
// type of event. Set to true if you need it, false otherwise.
this.CanHandlePowerEvent = false;
this.CanHandleSessionChangeEvent = false;
this.CanPauseAndContinue = false;
this.CanShutdown = true;
this.CanStop = true;
try
{
_log = LogManager.GetLogger("CollectorService");
_log.Info("Connecting to db...");
_manger = new MailBoxManager(ConfigurationManager.ConnectionStrings["mail"], 25);
_log.Info("Creating collector service...");
_collector = new Collector(_manger, MailQueueSettings.FromConfig);
_log.Info("Service is ready.");
AggregatorLogger.Instance.Initialize(_manger, GetServiceIp());
_log.Info("Aggregator logger initialized.");
}
catch (Exception ex)
{
_log.Fatal("CollectorService error under constuct: {0}", ex.ToString());
}
}
示例5: Run
private int Run()
{
Bootstrap();
_logger = _container.Resolve<Logger>();
var exitCode = HostFactory.Run(host =>
{
host.Service<RefreshService>(svc =>
{
svc.ConstructUsing(() =>
{
var agent = new RefreshService(RefreshInterval, () => _container.Resolve<RabbitMonitorRepository>() as RabbitMonitorRepository);
agent.OnReport += (s, e) => _logger.Trace(e.Data);
agent.OnError += (s, e) => _logger.Fatal(e.Data);
return agent;
});
svc.WhenStarted(a => a.Start());
svc.WhenStopped(a => a.Stop());
});
host.SetDescription("Refresh Service Agent for RabbitMQ");
host.SetDisplayName("RabbitMQ Refresh Agent");
host.SetServiceName("RabbitMQRefreshAgent");
host.RunAsNetworkService();
});
return (int)exitCode;
}
示例6: Main
static void Main(string[] args)
{
Database.SetInitializer<AwpContext>(null);
Database.SetInitializer<OenContext>(null);
Database.SetInitializer<HeatContext>(null);
try
{
Container = Bootstrap();
Runner = Container.Resolve<IJobsRunner>() as JobsRunner;
Runner.Title = "Automated Warming Process - Warmer Agent";
Runner.StartTime = DateTime.Now;
Log = Container.Resolve<Logger>();
Console.WriteLine("**************************************************************************");
Console.WriteLine("*");
Console.WriteLine("* {0} ", Runner.Title);
Console.WriteLine("* Date: {0} ", Runner.StartTime);
Console.WriteLine("*");
Console.WriteLine("* Usage:");
Console.WriteLine("*");
Console.WriteLine("* Warmer [-options] where options are:");
JobsRunner.CommandLineOptions.ToList().ForEach(x => Console.WriteLine("* {0}", x));
Console.WriteLine("*");
Console.WriteLine("**************************************************************************");
Console.WriteLine("\n\n\n");
Log.Trace("Starting the Process with Command Line: {0}", args.Dump());
PrepareRunner();
Runner.ParseCommandLine(args);
Runner.SetDefaultValuesForSettings();
Runner.BuildJobs();
Runner.ApplySettings();
Run();
}
catch (Exception e)
{
Log.Fatal(e.Message);
}
Console.WriteLine("\n\n\n");
Console.WriteLine("**************************************************************************");
Console.WriteLine("*");
Console.WriteLine("* Duration: {0} ", Runner.Duration);
Console.WriteLine("*");
Console.WriteLine("**************************************************************************");
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
Console.ReadLine();
}
#endif
}
示例7: Main
/// <summary>
/// Point d'entrée.
/// </summary>
static void Main(string[] args)
{
_logger = LogManager.GetLogger("Program");
if (!Environment.UserInteractive)
{
#region Considère un contexte de service
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service.MemcachedService()
};
ServiceBase.Run(ServicesToRun);
#endregion
}
else
{
#region Considère un contexte utilisateur (interactif)
_logger.Trace("Mode interactif");
int exitCode = 0;
try
{
#region Parse la ligne de commande
Options options = new Options();
ICommandLineParser parser = new CommandLineParser(new CommandLineParserSettings(false, true, Console.Error));
bool parserSucceed = parser.ParseArguments(args, options);
#endregion
if (options.Install || options.Uninstall)
{
if (!parserSucceed)
throw new ArgumentException("Ligne de commande invalide.");
Service.MemcachedServiceInstaller.Install(options.Uninstall, args);
return;
}
using (var service = new Service.MemcachedService())
{
service.SetUp(!parserSucceed ? args.Length != 0 ? args : AppSettings.GetMemcachedArguments() : AppSettings.GetMemcachedArguments());
_logger.Info("Service démarré. Appuyez sur ECHAP pour mettre fin au service...");
while (!NativeMethods.PeekEscapeKey()) { }
_logger.Info("[ESC]");
service.TearDown();
}
}
catch (Exception ex)
{
_logger.Fatal(ex.ToString());
exitCode = -1;
}
Environment.Exit(exitCode);
#endregion
}
}
示例8: Handle
public void Handle(AfcHotmailHeatData heatData, Logger logger)
{
try
{
using (var ctx = new HeatHotmailContext())
{
ctx.BulkInsert(new[] { heatData });
}
}
catch (DbEntityValidationException e)
{
logger.Fatal(e.Dump());
throw;
}
catch (Exception e)
{
logger.Fatal(e.Dump());
throw;
}
}
示例9: Main
static void Main(string[] args)
{
ConfigurationItemFactory.Default.Targets.RegisterDefinition("SignalTarget", typeof(SignalTarget));
Logger = LogManager.GetCurrentClassLogger(typeof(SignalTarget));
var rnd = new Random((int)DateTime.Now.Ticks);
for (int i = 0; i < 100; i++) {
Logger.Trace("Sample trace message from NLog");
Logger.Debug("Sample debug message from NLog");
Logger.Info("Sample informational message from NLog");
Logger.Warn("Sample warning message from NLog");
Logger.Error("Sample error message from NLog", new Exception("Something bad happened!"));
Logger.Fatal("Sample fatal error message from NLog");
var sleep = rnd.Next(20, 250);
Console.WriteLine(string.Concat("Sleeping...:", sleep, "ms"));
Thread.Sleep(sleep);
}
Console.WriteLine("Logging Complete. Press enter to continue...");
Console.ReadLine();
}
示例10: OnInitialized
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
try
{
// initialize logging panel
InitUILogging(LogLevel.Info);
logger = LogManager.GetCurrentClassLogger();
// create node
bitSharpNode = new BitSharpNode(Environment.GetCommandLineArgs(), strictArgs: false);
// initialize dummy wallet monitor
dummyMonitor = new DummyMonitor(bitSharpNode.CoreDaemon);
// setup view model
viewModel = new MainWindowViewModel(bitSharpNode.Kernel, dummyMonitor);
DataContext = viewModel;
// start node
bitSharpNode.StartAsync().Forget();
// start wallet monitor
Task.Run(() => dummyMonitor.Start());
}
catch (Exception ex)
{
if (logger != null)
{
logger.Fatal(ex, "Application failed:");
}
else
{
MessageBox.Show($"Application failed: {ex.Message}");
}
}
}
示例11: Main
static void Main(string[] args)
{
// Creating Needed Instances
RequestsHandler httpClient = new RequestsHandler ();
AppStoreParser parser = new AppStoreParser ();
// Loading Configuration
LogSetup.InitializeLog ("Apple_Store_Urls_Worker.log", "info");
_logger = LogManager.GetCurrentClassLogger ();
// Loading Config
_logger.Info ("Loading Configurations from App.config");
LoadConfiguration ();
// Control Variable (Bool - Should the process use proxies? )
bool shouldUseProxies = false;
// Checking for the need to use proxies
if (args != null && args.Length == 1)
{
// Setting flag to true
shouldUseProxies = true;
// Loading proxies from .txt received as argument
String fPath = args[0];
// Sanity Check
if (!File.Exists (fPath))
{
_logger.Fatal ("Couldnt find proxies on path : " + fPath);
System.Environment.Exit (-100);
}
// Reading Proxies from File
string[] fLines = File.ReadAllLines (fPath, Encoding.GetEncoding ("UTF-8"));
try
{
// Actual Load of Proxies
ProxiesLoader.Load (fLines.ToList ());
}
catch (Exception ex)
{
_logger.Fatal (ex);
System.Environment.Exit (-101);
}
}
// AWS Queue Handler
_logger.Info ("Initializing Queues");
AWSSQSHelper appsUrlQueue = new AWSSQSHelper (_appUrlsQueueName , _maxMessagesPerDequeue, _awsKey, _awsKeySecret);
AWSSQSHelper appsDataQueue = new AWSSQSHelper (_appsDataQueueName, _maxMessagesPerDequeue, _awsKey, _awsKeySecret);
// Setting Error Flag to No Error ( 0 )
System.Environment.ExitCode = 0;
// Initialiazing Control Variables
int fallbackWaitTime = 1;
_logger.Info ("Started Processing Individual Apps Urls");
do
{
try
{
// Dequeueing messages from the Queue
if (!appsUrlQueue.DeQueueMessages ())
{
Thread.Sleep (_hiccupTime); // Hiccup
continue;
}
// Checking for no message received, and false positives situations
if (!appsUrlQueue.AnyMessageReceived ())
{
// If no message was found, increases the wait time
int waitTime;
if (fallbackWaitTime <= 12)
{
// Exponential increase on the wait time, truncated after 12 retries
waitTime = Convert.ToInt32 (Math.Pow (2, fallbackWaitTime) * 1000);
}
else // Reseting Wait after 12 fallbacks
{
waitTime = 2000;
fallbackWaitTime = 0;
}
fallbackWaitTime++;
// Sleeping before next try
Console.WriteLine ("Fallback (seconds) => " + waitTime);
Thread.Sleep (waitTime);
continue;
}
// Reseting fallback time
fallbackWaitTime = 1;
// Iterating over dequeued Messages
//.........這裏部分代碼省略.........
示例12: Main
/// <summary>
/// Entry point of the crawler
/// </summary>
/// <param name="args"></param>
static void Main (string[] args)
{
// Setting Up Log
LogSetup.InitializeLog ("PlayStoreCrawler.log", "info");
_logger = LogManager.GetCurrentClassLogger ();
// Control Variable (Bool - Should the process use proxies? )
bool isUsingProxies = false;
// Checking for the need to use HTTP proxies or not
if (args != null && args.Length == 1)
{
_logger.Info ("Loading Proxies from File");
// Setting flag to true
isUsingProxies = true;
// Loading proxies from .txt received as argument
String fPath = args[0];
// Sanity Check
if (!File.Exists (fPath))
{
_logger.Fatal ("Couldnt find proxies on path : " + fPath);
System.Environment.Exit (-100);
}
// Reading Proxies from File
string[] fLines = File.ReadAllLines (fPath, Encoding.GetEncoding ("UTF-8"));
try
{
// Actual Load of Proxies
ProxiesLoader.Load (fLines.ToList ());
}
catch (Exception ex)
{
_logger.Fatal (ex);
System.Environment.Exit (-101);
}
}
// Main Flow
_logger.Info ("Started Bootstrapping Steps");
// Scrapping "Play Store Categories"
foreach (var categoriesKVP in BootstrapTerms.categoriesAndNames)
{
CrawlCategory (categoriesKVP.Key, categoriesKVP.Value, isUsingProxies);
}
// Queueing Apps that start with each of the characters from "A" to "Z"
foreach (var character in BootstrapTerms.charactersSearchTerms)
{
CrawlStore (character, isUsingProxies);
}
/// ... Keep Adding characters / search terms in order to increase the crawler's reach
// APP CATEGORIES
foreach (var category in BootstrapTerms.categoriesSearchTerms)
{
CrawlStore (category, isUsingProxies);
}
// Extra "Random" Search terms to increase even more the crawler's reach
foreach (var miscTerm in BootstrapTerms.miscSearchTerms)
{
CrawlStore (miscTerm, isUsingProxies);
}
// Country Names as Search terms to increase even more the crawler's reach
foreach (var countryName in BootstrapTerms.countryNames)
{
CrawlStore (countryName, isUsingProxies);
}
}
示例13: VerifyMessagesInMockChannel
private void VerifyMessagesInMockChannel(Logger aiLogger, string instrumentationKey)
{
aiLogger.Trace("Sample trace message");
aiLogger.Debug("Sample debug message");
aiLogger.Info("Sample informational message");
aiLogger.Warn("Sample warning message");
aiLogger.Error("Sample error message");
aiLogger.Fatal("Sample fatal error message");
AdapterHelper.ValidateChannel(this.adapterHelper, instrumentationKey, 6);
}
示例14: Main
static void Main(string[] args)
{
// Creating Needed Instances
RequestsHandler httpClient = new RequestsHandler ();
AppStoreParser parser = new AppStoreParser ();
// Setting Up Log
LogSetup.InitializeLog ("Apple_Store_Crawler.log", "info");
_logger = LogManager.GetCurrentClassLogger ();
// Starting Flow
_logger.Info ("Worker Started");
// Loading Configuration
_logger.Info ("Reading Configuration");
LoadConfiguration ();
// Control Variable (Bool - Should the process use proxies? )
bool shouldUseProxies = false;
// Checking for the need to use proxies
if (args != null && args.Length == 1)
{
// Setting flag to true
shouldUseProxies = true;
// Loading proxies from .txt received as argument
String fPath = args[0];
// Sanity Check
if (!File.Exists (fPath))
{
_logger.Fatal ("Couldnt find proxies on path : " + fPath);
System.Environment.Exit (-100);
}
// Reading Proxies from File
string[] fLines = File.ReadAllLines (fPath, Encoding.GetEncoding ("UTF-8"));
try
{
// Actual Load of Proxies
ProxiesLoader.Load (fLines.ToList ());
}
catch (Exception ex)
{
_logger.Fatal (ex);
System.Environment.Exit (-101);
}
}
// AWS Queue Handler
_logger.Info ("Initializing Queues");
AzureSQSHelper sqsWrapper = new AzureSQSHelper (_categoriesQueueName, 10, _azureQueueconn);
// Step 1 - Trying to obtain the root page html (source of all the apps)
var rootPageResponse = httpClient.GetRootPage (shouldUseProxies);
// Sanity Check
if (String.IsNullOrWhiteSpace (rootPageResponse))
{
_logger.Info ("Error obtaining Root Page HTMl - Aborting", "Timeout Error");
return;
}
// Step 2 - Extracting Category Urls from the Root Page and queueing their Urls
foreach (var categoryUrl in parser.ParseCategoryUrls (rootPageResponse))
{
// Logging Feedback
_logger.Info ("Queueing Category : " + categoryUrl);
// Queueing Category Urls
sqsWrapper.EnqueueMessage (categoryUrl);
}
_logger.Info ("End of Bootstrapping phase");
//Console.ReadLine();
}
示例15: Main
/// <summary>
/// Main application entry point.
/// </summary>
/// <param name="args">Input arguments.</param>
/// <returns>The application exit code.</returns>
public static int Main(string[] args)
{
string logPath = null, watcherThreshhold = null;
int enableLogging = 0, verbose = 0, help = 0;
var options = new OptionSet()
{
{ "d|directory=", "(required) the path to the application directory of the application to run jobs for.", v => directory = v },
{ "c|config=", "the path to the configuration file to use.", v => config = v },
{ "v|verbose", "write session output to the console.", v => { ++verbose; } },
{ "l|log", "write session output to a log file.", v => { ++enableLogging; } },
{ "lf|logfile=", "the path to the log file to write to.", v => logPath = v },
{ "p|persistence=", "the path to the running jobs persistence path to create/user.", v => persistencePath = v },
{ "t|threshold=", "the threshold, in milliseconds, to compress filesystem events into.", v => watcherThreshhold = v },
{ "h|help", "display usage help.", v => { ++help; } }
};
try
{
options.Parse(args);
directory = PathQuotesExp.Replace(directory ?? String.Empty, "$1");
config = PathQuotesExp.Replace(config ?? String.Empty, "$1");
logPath = PathQuotesExp.Replace(logPath ?? String.Empty, "$1");
persistencePath = PathQuotesExp.Replace(persistencePath ?? String.Empty, "$1");
}
catch (OptionException ex)
{
ShowHelp(options, ex);
return 1;
}
if (help > 0)
{
ShowHelp(options, null);
return 0;
}
if (enableLogging > 0 && String.IsNullOrEmpty(logPath))
{
logPath = Path.GetFullPath("collar.log");
}
LogManager.Configuration = CreateLoggingConfiguration(verbose > 0, enableLogging > 0, logPath);
logger = LogManager.GetLogger("BlueCollar");
if (String.IsNullOrEmpty(directory))
{
ShowHelp(options, new ArgumentException("You must specify the directory of an application to run jobs for."));
return 1;
}
else if (!Directory.Exists(directory))
{
string message = String.Format(CultureInfo.InvariantCulture, "The application directory '{0}' does not exist.", directory);
if (verbose > 0)
{
logger.Fatal(message);
}
else
{
Console.Error.WriteLine(message);
}
return 1;
}
if (!String.IsNullOrEmpty(config) && !File.Exists(config))
{
string message = String.Format(CultureInfo.InvariantCulture, "The configuration file '{0}' does not exist.", config);
if (verbose > 0)
{
logger.Fatal(message);
}
else
{
Console.Error.WriteLine(message);
}
return 1;
}
if (String.IsNullOrEmpty(persistencePath))
{
string above = Path.GetDirectoryName(directory);
if (!String.IsNullOrEmpty(above))
{
persistencePath = Path.GetFullPath(directory.Substring(above.Length + 1) + ".bin");
logger.Info(CultureInfo.InvariantCulture, "Using defaulted running jobs persistence file at '{0}'.", persistencePath);
}
}
if (!String.IsNullOrEmpty(watcherThreshhold))
{
//.........這裏部分代碼省略.........