public void Fatal(string str, [CallerLineNumber] int lineNumber = 0, [CallerMemberName] string caller = null, [CallerFilePath] string filepath = null) { logger?.Fatal(Bake(str, lineNumber, caller, filepath)); }
/// <summary> /// Log写入 /// </summary> /// <param name="logBean"></param> public void WriteLog(MsgLevel level, string message) { switch (level) { case MsgLevel.Debug: basicLog?.Debug(message); break; case MsgLevel.Info: basicLog?.Info(message); break; case MsgLevel.Warn: basicLog?.Warn(message); break; case MsgLevel.Error: errLog?.Error(message); break; case MsgLevel.Fatal: errLog?.Fatal(message); break; } }
public AudioManager(bool hardware = true) { _log = Logging.LogManager.GetLogger(this); _log.Info("Initializing AudioManager..."); _log.Info("Creating FMOD system..."); uint version = 0; RESULT result = Factory.System_Create(ref _system); ErrCheck(result); _log.Debug("Checking FMOD version..."); result = _system.getVersion(ref version); ErrCheck(result); if (version < VERSION.number) { var msg = string.Format("Error! You are using an old version of FMOD: {0}. This program requires: {1}.", version.ToString("X"), VERSION.number.ToString("X")); _log.Fatal(msg); throw new FMODException(msg); } result = _system.init(MaxChannels, INITFLAGS.NORMAL, (IntPtr) null); ErrCheck(result); _soundManager = new SoundManager(_system, hardware); _songManager = new SongManager(_system, hardware); _log.Info("AudioManager initialized!"); }
public void WriteLog(LogEnum name, LogLevel level, string logContent) { log = log4net.LogManager.GetLogger(name.ToString()); //log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); switch (level) { case LogLevel.DEBUG: log.Debug(logContent); break; case LogLevel.ERROR: log.Error(logContent); break; case LogLevel.FATAL: log.Fatal(logContent); break; case LogLevel.INFO: log.Info(logContent); break; case LogLevel.WARN: log.Warn(logContent); break; default: log.Debug(logContent); break; } }
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { try { if (!AppDataFolder.Exists) { AppDataFolder.Create(); } var ex = e.ExceptionObject as Exception; if (ex != null) { var content = $"{ex.GetType().Name}{Environment.NewLine}HResult:{ex.HResult}{Environment.NewLine}Message:{ex.Message}{Environment.NewLine}Source:{ex.Source}{Environment.NewLine}StackTrace:{ex.StackTrace}{Environment.NewLine}InnerException:{ex.InnerException}{Environment.NewLine}"; File.WriteAllText(Path.Combine(AppDataFolder.FullName, "crashexception.txt"), content); } Log?.Fatal("Unhandled exception in application.", e.ExceptionObject as Exception); } catch {} }
/// <summary>Adds Fatal log.</summary> /// <param name="log">Log string.</param> public static void AddFatal(string log) { _logger.Fatal(log); }
public ActionResult Import(Guid id) { try { var clients = db.ImportClientFundStatusProc(id).ToList(); var IsraelCashSerNumber = System.Web.Configuration.WebConfigurationManager.AppSettings["IsraelCashSerNumber"].Parse <int>(); var cfsClients = clients.Where(c => c.AgencyGroupId == IsraelCashSerNumber).ToList(); var context = System.Web.HttpContext.Current; new Thread(delegate() { try { var sendClients = clients.Where(c => c.LeaveReasonId == null || c.LeaveReasonId != (int)LeaveReasonEnum.Deceased).ToList(); var approvalStatusSend = new List <ImportClientFundStatusProc_Result>(); var hcStatusSend = new List <ImportClientFundStatusProc_Result>(); foreach (var c in sendClients) { //sp returns clients with approval OR hc status changed if (c.OldHcStatusId != c.NewHcStatusId && c.OldApprovalStatusId == c.NewApprovalStatusId) { hcStatusSend.Add(c); } else if (c.OldApprovalStatusId != c.NewApprovalStatusId) { approvalStatusSend.Add(c); } } if (approvalStatusSend.Count > 0) { SendStatusChangeNotifications(sendClients); //set as job } if (hcStatusSend.Any()) { using (var j = new CC.Web.Jobs.HcStatusChangeNotificationsJob()) { var groupedBySer = hcStatusSend.GroupBy(f => f.AgencyGroupId).Select(f => new ClientsHcStatusChangeEmailModel { AgencyGroupId = f.Key, Clients = f.Select(c => new ClientHcStatusChangeEmailModel { ClientId = c.ClientId ?? 0, ClientName = c.FirstName + " " + c.LastName, ApprovalStatusName = ((ApprovalStatusEnum)c.NewApprovalStatusId).DisplayName(), BirthCountryName = c.BirthCountryName, CountryName = c.CountryName, HcStatusName = c.HcStatusName, AgencyId = c.AgencyId }) }); j.SendNotifications(groupedBySer); } } if (cfsClients.Count > 0) { CC.Web.Controllers.ClientsController.ExportCsvForChangedApprovalStatus(cfsClients); } } catch (Exception ex) { _log.Error(ex); } }).Start(); return(RedirectToAction("Index")); } catch (System.Data.EntityCommandExecutionException ex) { _log.Fatal(ex.Message, ex); ModelState.AddModelError(string.Empty, ex.InnerException.Message); } catch (Exception ex) { _log.Fatal(ex.Message, ex); ModelState.AddModelError(string.Empty, ex); } return(View("Preview", id)); }
/// <summary> /// /// </summary> /// <param name="obj"></param> public void Fatal(object obj) { _fatal.Fatal(obj); }
static public void Main(string[] Args) { //Upgrade settings System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); Version appVersion = a.GetName().Version; string appVersionString = appVersion.ToString(); log.DebugFormat("Application version of new settings {0}", appVersionString); try { if (Properties.Settings.Default.ApplicationVersion != appVersion.ToString()) { log.Debug("Upgrading settings..."); Properties.Settings.Default.Upgrade(); // if program's hash has changed (e.g. by upgrading to .NET 4.0), then Upgrade() doesn't import the previous application settings // because it cannot locate a previous user.config file. In this case a new user.config file is created with the default settings. // We will try and find a config file from a previous installation and update the settings from it if (Properties.Settings.Default.ApplicationVersion == "" && Properties.Settings.Default.DoUpgrade) { SettingsUpdate.Update(); } log.DebugFormat("Settings upgraded from '{0}' to '{1}'", Properties.Settings.Default.ApplicationVersion, appVersionString); Properties.Settings.Default.ApplicationVersion = appVersionString; Settings.TrySaveSettings(); } } catch (ConfigurationErrorsException ex) { log.Error("Could not load settings.", ex); var msg = string.Format("{0}\n\n{1}", Messages.MESSAGEBOX_LOAD_CORRUPTED_TITLE, string.Format(Messages.MESSAGEBOX_LOAD_CORRUPTED, Settings.GetUserConfigPath())); var dlog = new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Error, msg, Messages.XENCENTER)) { StartPosition = FormStartPosition.CenterScreen, //For reasons I do not fully comprehend at the moment, the runtime //overrides the above StartPosition with WindowsDefaultPosition if //ShowInTaskbar is false. However it's a good idea anyway to show it //in the taskbar since the main form is not launcched at this point. ShowInTaskbar = true }; dlog.ShowDialog(); Application.Exit(); return; } // Reset statics, because XenAdminTests likes to call Main() twice. TestExceptionString = null; Exiting = false; // Clear XenConnections and History so static classes like OtherConfigAndTagsWatcher // listening to changes still work when Main is called more than once. ConnectionsManager.XenConnections.Clear(); ConnectionsManager.History.Clear(); Search.InitSearch(Branding.Search); TreeSearch.InitSearch(); ArgType argType = ArgType.None; AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadException -= Application_ThreadException; Application.ThreadException += Application_ThreadException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { if (SystemInformation.FontSmoothingType == 2) // ClearType { TransparentUsually = SystemColors.Window; } } catch (NotSupportedException) { // Leave TransparentUsually == Color.Transparent. This is an old platform // without FontSmoothingType support. } switch (Environment.OSVersion.Version.Major) { case 6: // Vista, 2K8, Win7. if (Application.RenderWithVisualStyles) { // Vista, Win7 with styles. TitleBarStartColor = Color.FromArgb(242, 242, 242); TitleBarEndColor = Color.FromArgb(207, 207, 207); TitleBarBorderColor = Color.FromArgb(160, 160, 160); TitleBarForeColor = Color.FromArgb(60, 60, 60); HeaderGradientForeColor = Color.White; HeaderGradientFont = new Font(DefaultFont.FontFamily, 11.25f); HeaderGradientFontSmall = DefaultFont; TabbedDialogHeaderFont = HeaderGradientFont; TabPageRowBorder = Color.Gainsboro; TabPageRowHeader = Color.WhiteSmoke; } else { // 2K8, and Vista, Win7 without styles. TitleBarForeColor = SystemColors.ControlText; HeaderGradientForeColor = SystemColors.ControlText; HeaderGradientFont = new Font(DefaultFont.FontFamily, DefaultFont.Size + 1f, FontStyle.Bold); HeaderGradientFontSmall = DefaultFontBold; TabbedDialogHeaderFont = HeaderGradientFont; TabPageRowBorder = Color.DarkGray; TabPageRowHeader = Color.Silver; } break; default: TitleBarStartColor = ProfessionalColors.OverflowButtonGradientBegin; TitleBarEndColor = ProfessionalColors.OverflowButtonGradientEnd; TitleBarBorderColor = TitleBarEndColor; TitleBarForeColor = Application.RenderWithVisualStyles ? Color.White : SystemColors.ControlText; HeaderGradientForeColor = TitleBarForeColor; HeaderGradientFont = new Font(DefaultFont.FontFamily, DefaultFont.Size + 1f, FontStyle.Bold); HeaderGradientFontSmall = DefaultFontBold; TabbedDialogHeaderFont = new Font(DefaultFont.FontFamily, DefaultFont.Size + 1.75f, FontStyle.Bold); TabPageRowBorder = Color.DarkGray; TabPageRowHeader = Color.Silver; break; } // Force the current culture, to make the layout the same whatever the culture of the underlying OS (CA-46983). Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo(InvisibleMessages.LOCALE, false); if (string.IsNullOrEmpty(Thread.CurrentThread.Name)) { Thread.CurrentThread.Name = "Main program thread"; } ServicePointManager.DefaultConnectionLimit = 20; ServicePointManager.ServerCertificateValidationCallback = SSL.ValidateServerCertificate; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; XenAPI.Session.UserAgent = string.Format("XenCenter/{0}", ClientVersion()); ReconfigureConnectionSettings(); log.Info("Application started"); logSystemDetails(); OptionsDialog.Log(); if (Args.Length > 0) { log.InfoFormat("Args[0]: {0}", Args[0]); } List <string> sanitizedArgs = new List <string>(Args); // Remove the '--wait' argument, which may have been passed to the splash screen sanitizedArgs.Remove("--wait"); string[] args = null; if (sanitizedArgs.Count > 1) { argType = ParseFileArgs(sanitizedArgs, out args); if (argType == ArgType.Passwords) { log.DebugFormat("Handling password request using '{0}'", args[0]); try { PasswordsRequest.HandleRequest(args[0]); } catch (Exception exn) { log.Fatal(exn, exn); } Application.Exit(); return; } } else if (sanitizedArgs.Count == 1 && sanitizedArgs[0] == "messageboxtest") { new Dialogs.MessageBoxTest().ShowDialog(); Application.Exit(); return; } else if (sanitizedArgs.Count > 0) { log.Warn("Unrecognised command line options"); } try { ConnectPipe(); } catch (System.ComponentModel.Win32Exception exn) { log.Error("Creating named pipe failed. Continuing to launch XenCenter.", exn); } Application.ApplicationExit -= Application_ApplicationExit; Application.ApplicationExit += Application_ApplicationExit; MainWindow mainWindow = new MainWindow(argType, args); Application.Run(mainWindow); log.Info("Application main thread exited"); }
public static void WriteLog(EnumLogLevel logLevel, string methedName, string actionName, string controllerName, string message, Exception exception) { var request = HttpContext.Current.Request; string user; try { user = ApplicationContext.Current.UserName; } catch { user = "******"; } var logMessage = new LogMessage(0, user, 0 , string.Format("{3}, 控制器:{0},动作:{1},Message:{2}" , controllerName, actionName, message, methedName) , request.UserHostAddress, request.Browser.Platform , request.Browser.Browser + request.Browser.Version); switch (logLevel) { case EnumLogLevel.Fatal: { log.Fatal(logMessage, exception); break; } case EnumLogLevel.Error: { log.Error(logMessage, exception); break; } case EnumLogLevel.Warning: { log.Warn(logMessage); break; } case EnumLogLevel.Info: { log.Info(logMessage); break; } case EnumLogLevel.Debug: { log.Debug(logMessage); break; } default: { log.Fatal(new LogMessage(0, user, 0 , string.Format("{0},logLevel error", methedName) , request.UserHostAddress, request.Browser.Platform , request.Browser.Browser + request.Browser.Version), exception); break; } } }
public void Fatal(object message) { _log.Fatal(message.ToString()); }
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler; #if DEBUG bool debug = true; #else bool debug = false; #endif if (args.Length > 0) if (args[0].ToLower() == "debug") debug = true; if (string.IsNullOrEmpty(Thread.CurrentThread.Name)) Thread.CurrentThread.Name = "Main"; if (debug && !System.Diagnostics.Debugger.IsAttached) { AllocConsole(); IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE); var safeFileHandle = new SafeFileHandle(stdHandle, true); var fileStream = new FileStream(safeFileHandle, FileAccess.Write); var encoding = System.Text.Encoding.GetEncoding(CODE_PAGE); var stdOut = new StreamWriter(fileStream, encoding) {AutoFlush = true}; Console.SetOut(stdOut); } LogManager.LoadConfig(debug); _log = LogManager.GetLogger(typeof (Program)); _log.Info("!!! APPLICATION LOAD !!!"); _log.Info("Detecting components..."); foreach (var file in Directory.GetFiles(Directory.GetCurrentDirectory())) { string ext = Path.GetExtension(file); if (string.IsNullOrEmpty(ext)) continue; ext = ext.Substring(1); if (ext == "dll" || ext == "exe") { string version = AssemblyName.GetAssemblyName(file).Version.ToString(); string name = Path.GetFileNameWithoutExtension(file); _log.Info(name + " v" + version); } } _log.Info("Components detected!"); _log.Info("Sharpcraft is loading..."); try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (!Directory.Exists(Constants.SettingsDirectory)) Directory.CreateDirectory(Constants.SettingsDirectory); #if SC_DIRECT new Sharpcraft(null).Run(); #else _log.Debug("Starting launcher..."); _launcher = new Launcher(); _launcher.Show(); _context = new ApplicationContext(_launcher); Application.Run(_context); _log.Info("Launcher has returned execution to main thread."); #endif } catch(FileNotFoundException ex) { _log.Fatal("Required file \"" + ex.FileName + "\" not found! Application is exiting..."); } catch(IOException ex) { _log.Fatal("IO Operation failed: " + ex.Message); _log.Fatal("Application is exiting..."); } catch(Exception ex) { UnhandledExceptionHandler(null, new UnhandledExceptionEventArgs(ex, false)); #if DEBUG throw; #endif } finally { if (_launcher != null) { _log.Debug("Closing launcher."); _launcher.Close(); _launcher.Dispose(); _launcher = null; _log.Info("Launcher closed."); } if (debug) { _log.Debug("Closing debug console."); FreeConsole(); } _log.Info("!!! APPLICATION EXIT !!!"); } }
public IceManager(string adapterName, string host, int port, bool catchSignals = true) { IceGridHost = host; IceGridPort = port; Name = adapterName; logger = log4net.LogManager.GetLogger(this.GetType().Name + "::" + Name); _ServantIds = new List<Ice.Identity>(); //keep track of servants for emergency cleanup string myIP = findLocalIPAddress(); logger.Info("My IPAddress is: " + myIP); //initialize Ice Ice.Properties prop = Ice.Util.createProperties(); prop.setProperty("hms.AdapterId", adapterName); prop.setProperty("hms.Endpoints", "tcp -h " + myIP + ":udp -h " + myIP); prop.setProperty("Ice.Default.Locator", "IceGrid/Locator:tcp -p " + IceGridPort + " -h " + IceGridHost); prop.setProperty("Ice.ThreadPool.Server.Size", "5"); prop.setProperty("Ice.ThreadPool.Server.SizeMax", "100000"); prop.setProperty("Ice.ThreadPool.Client.Size", "5"); prop.setProperty("Ice.ThreadPool.Client.SizeMax", "100000"); Ice.InitializationData iceidata = new Ice.InitializationData(); iceidata.properties = prop; Communicator = Ice.Util.initialize(iceidata); // could add sys.argv try { _Adapter = Communicator.createObjectAdapter("hms"); _Adapter.activate(); } catch (Exception ex) { logger.Fatal("Network error, check configuration: " + ex.Message); logger.Fatal("Endpoint(should be local machine): " + prop.getProperty("hms.Endpoints")); logger.Fatal("Locator (should be IceGrid Server): " + prop.getProperty("Ice.Default.Locator")); throw (ex); // we are dead anyway } //Now are we ready to communicate with others //getting usefull proxies try { // proxy to icegrid to register our vc devices Query = IceGrid.QueryPrxHelper.checkedCast(Communicator.stringToProxy("IceGrid/Query")); if (Query == null) { logger.Error("invalid ICeGrid proxy"); } // proxy to icestorm to publish events EventMgr = IceStorm.TopicManagerPrxHelper.checkedCast(Communicator.stringToProxy("EventServer/TopicManager")); if (EventMgr == null) { logger.Error("invalid IceStorm proxy"); } //these 2 objects are only needed to get the IceGrid admin object in order to register _Registry = IceGrid.RegistryPrxHelper.uncheckedCast(Communicator.stringToProxy("IceGrid/Registry")); updateIceGridAdmin(); } catch (Ice.NotRegisteredException e) { logger.Fatal("If we fail here it is probably because the Icebox objects are not registered: " + e.Message); } catch (Exception e) { logger.Fatal("IceGrid Server not found!!!!!: " + e.Message); throw (e);//without yellow page system, there is no need to start } if (catchSignals) { setupSignals(); } }
static void Main(string[] args) { try { basePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); addresses = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName()); string url = "/Btnm/LocalPlatform"; string addr = "tcp://127.0.0.1:7070"; foreach (string ss in args) { if (ss.StartsWith("--Url=", StringComparison.InvariantCultureIgnoreCase)) { url = ss.Substring("--Url=".Length); } else if (ss.StartsWith("--Address=", StringComparison.InvariantCultureIgnoreCase)) { addr = ss.Substring(10); } else if (ss.StartsWith("--MaxSize=", StringComparison.InvariantCultureIgnoreCase)) { maxSize = int.Parse(ss.Substring(10)); } } XmlSetting xmlSetting = new XmlSetting(new StreamReader(Path.Combine(basePath, "nanrui.modul.config"))); defaultSetting = XmlSetting.ReadFromFile(Path.Combine(basePath, "../nanrui.default.config")); log4net.Config.XmlConfigurator.Configure(xmlSetting.SelectOne("/configuration/log4net").AsXmlNode() as System.Xml.XmlElement); logger = log4net.LogManager.GetLogger("Betanetworks"); try { cachePath = Path.Combine(basePath, "cache"); profix = defaultSetting.ReadSetting("/configuration/Locale/PrefixId/@value", profix); corporation = defaultSetting.ReadSetting("/configuration/Locale/Corporation/@value", corporation); uploadForPCAgent = "true" == xmlSetting.ReadSetting("/configuration/Locale/UploadForPCAgent/@value", "false"); uploadForBadLink = "true" == xmlSetting.ReadSetting("/configuration/Locale/UploadForBadLink/@value", "false"); supportMultCPU = "true" == xmlSetting.ReadSetting("/configuration/Locale/SupportMultCPU/@value", "false"); logger.InfoFormat("配置发送程序启动,缺省前缀 '{0}',缺省公司 '{1}'", profix, corporation); logger.Info("载入设备指标映射!"); DispatchImpl.ReadDispatch(xmlSetting.SelectOne("/configuration/Maps/Device"), _deviceDispatcher, logger); logger.Logger.Log(typeof(Dispatcher), log4net.Core.Level.Trace, "载入要发送的设备备注列表!", null); ReadMap(_deviceFields, xmlSetting.Select("/configuration/Locale/DeviceFields/*")); logger.Logger.Log(typeof(Dispatcher), log4net.Core.Level.Trace, "载入設備的公司列表!", null); ReadIni(_corporationIPSeg, xmlSetting.Select("/configuration/Locale/Corporations/*")); //<Corporations> // <IPAddress from="" to="" value="" /> //</Corporations> Dictionary<string, XmlContainer> dict = new Dictionary<string, XmlContainer>(); logger.Info("开始读设备表!"); IList<Device> devices = Device.FindBy<Device>(null); logger.Info("读设备表完成,开始处理!"); foreach (Device dev in devices) { XmlContainer xmlContainer = null; switch (dev.Catalog) { case 1: //交换机 logger.InfoFormat("开始处理交换机{0}:{1}:{2}!", dev.Id, dev.Address, dev); xmlContainer = processSW(dev, dict); break; case 2://路由器 logger.InfoFormat("开始处理路由器{0}:{1}:{2}!", dev.Id, dev.Address, dev); xmlContainer = processRT(dev, dict); break; case 3://交换路由器 logger.InfoFormat("开始处理交换路由器{0}:{1}:{2}!", dev.Id, dev.Address, dev); xmlContainer = processSW(dev, dict); break; default: logger.InfoFormat("跳过未知设备{0}:{1}:{2}!", dev.Id, dev.Address, dev); break; } if (null != xmlContainer) { _deviceByIds[dev.Id] = dev; clearXml(xmlContainer, dict); } } logger.Info("处理设备表完成,开始读线路表!"); using (linkLogger = new StreamWriter(Path.Combine(basePath, string.Concat("nanrui.modul.link.txt")))) { IList<Link> links = Link.FindBy<Link>(null); logger.Info("读线路表完成,开始处理!"); foreach (Link link in links) { logger.InfoFormat("开始处理线路{0}:{1}!", link.Id, link); XmlContainer xmlContainer = processLink(link, dict); clearXml(xmlContainer, dict); if (null != xmlContainer) { _linkByIds[link.Id] = link; clearXml(xmlContainer, dict); } } } linkLogger = null; logger.Info("处理线路表完成, 开始发送数据!"); foreach (XmlContainer xmlContainer in dict.Values) { XmlNode node = xmlContainer.Doc.SelectSingleNode("/IMSDATA/datas[@classname=\"RelationShip\"]"); if (null != node) { XmlNode parentNode = node.ParentNode; parentNode.RemoveChild(node); parentNode.AppendChild(node); } Send(xmlContainer.Doc, xmlContainer.Doc.OuterXml); } logger.Info("数据处理完成,配置发送程序退出!"); } catch (Exception e) { logger.Fatal("发生异常!", e); } } catch (Exception e) { Console.WriteLine(e); } }
public MainGame() { _log = LogManager.GetLogger(this); Activated += GameActivated; Deactivated += GameDeactivated; _log.Debug("Setting initial FPS value"); FPS = 0.0f; _log.Info("Setting graphics settings..."); _graphics = new GraphicsDeviceManager(this) { PreferredBackBufferWidth = ScreenWidth, PreferredBackBufferHeight = ScreenHeight }; _log.Info(string.Format("Screen size set to: [W]{0} x [H]{1}", ScreenWidth, ScreenHeight)); _graphics.SynchronizeWithVerticalRetrace = false; //IsFixedTimeStep = false; _graphics.ApplyChanges(); ScreenRectangle = new Rectangle(0, 0, ScreenWidth, ScreenHeight); _log.Debug("Setting content root directory..."); Content.RootDirectory = "Content"; // Create necessary folders if they don't exist try { if (!Directory.Exists(Paths.SettingsFolder)) Directory.CreateDirectory(Paths.SettingsFolder); } catch (IOException ex) { _log.Error("Failed to create necessary game folders. Exception details as follows..."); _log.Fatal("IOException: " + ex.Message + Environment.NewLine + "Details:", ex); _log.Fatal("Game will now exit..."); Exit(); } _log.Info("Loading controls..."); ControlsManager = new ControlsManager(); _log.Debug("Controls loaded!"); _log.Info("Creating components..."); AudioManager = new AudioManager(); _stateManager = new GameStateManager(this); TitleScreen = new TitleScreen(this, _stateManager); StartMenuScreen = new StartMenuScreen(this, _stateManager); CharacterGeneratorScreen = new CharacterGeneratorScreen(this, _stateManager); SkillScreen = new SkillScreen(this, _stateManager); LoadGameScreen = new LoadGameScreen(this, _stateManager); GamePlayScreen = new GamePlayScreen(this, _stateManager); Components.Add(new InputHandler(this)); Components.Add(_stateManager); _log.Info("Components created!"); LoadMusic(); var menuSong = AudioManager.Song.GetSong("MenuTheme"); menuSong.SetStartFade(new FadeInfo(0.0f, 1.0f, 0.01f, TimeSpan.FromMilliseconds(20))); menuSong.SetEndFade(new FadeInfo(1.0f, 0.0f, 0.01f, TimeSpan.FromMilliseconds(15))); _log.Debug("Changing to TitleScreen..."); _stateManager.ChangeState(TitleScreen); }
private void ProcessDatasetTask(int id) { //https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-based-asynchronous-programming?view=netframework-4.5.2 Task t = new Task(() => { try { using (IAnalystEdgarDatasetsRepository repository = CreateRepository()) { EdgarDataset ds = repository.GetDataset(id); if (ds != null) { ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////BEGIN PROCESS Stopwatch watch = System.Diagnostics.Stopwatch.StartNew(); log.Info("Datasetid " + id.ToString() + " -- BEGIN dataset process"); //Load Submissions, Tags and Dimensions EdgarTaskState[] states = LoadSubTagDim(ds, repository); bool ok = ManageErrors(states); log.Info(string.Format("Datasetid {0} -- Variables after LoadSubTagDim(..): ManageErrors: {1}; Submissions: {2}/{3}; Tags: {4}/{5}; Dimensions: {6}/{7}", id, ok, ds.ProcessedSubmissions, ds.TotalSubmissions, ds.ProcessedTags, ds.TotalTags, ds.ProcessedDimensions, ds.TotalDimensions)); if (!ok || ds.ProcessedSubmissions != ds.TotalSubmissions || ds.ProcessedTags != ds.TotalTags || ds.ProcessedDimensions != ds.TotalDimensions) { log.Fatal("Process of sub, tags or dims failed, process can't continue"); return; } //Retrieve all tags, submissions and dimensions to fill the relationship //Load Calculations, Texts and Numbers log.Info("Datasetid " + id.ToString() + " -- loading all tags for LoadCalTxtNum(...)"); ConcurrentDictionary <string, int> tags = tagService.GetAsConcurrent(id); log.Info("Datasetid " + id.ToString() + " -- loading all subs for LoadCalTxtNum(...)"); ConcurrentDictionary <string, int> subs = submissionService.GetAsConcurrent(id); log.Info("Datasetid " + id.ToString() + " -- loading all dims for LoadCalTxtNum(...)"); ConcurrentDictionary <string, int> dims = dimensionService.GetAsConcurrent(id); log.Info("Datasetid " + id.ToString() + " -- Starting LoadCalTxtNum(...)"); states = LoadCalTxtNum(ds, repository, subs, tags, dims); ok = ManageErrors(states); log.Info(string.Format("Datasetid {0} -- Variables after LoadCalTxtNum(..): ManageErrors: {1}; Calculations: {2}/{3}; Texts: {4}/{5}; Numbers: {6}/{7}", id, ok, ds.ProcessedCalculations, ds.TotalCalculations, ds.ProcessedTexts, ds.TotalTexts, ds.ProcessedNumbers, ds.TotalNumbers)); if (!ok || ds.ProcessedCalculations != ds.TotalCalculations || ds.ProcessedTexts != ds.TotalTexts || ds.ProcessedNumbers != ds.TotalNumbers) { log.Fatal("Process of cal, text or nums failed, process can't continue"); return; } log.Info("Datasetid " + id.ToString() + " -- releasing dims"); dims.Clear(); dims = null; //Load Presentations and Renders log.Info("Datasetid " + id.ToString() + " -- loading all nums for LoadRenPre(...)"); ConcurrentDictionary <string, int> nums = numService.GetAsConcurrent(id); log.Info("Datasetid " + id.ToString() + " -- loading all txt for LoadRenPre(...)"); ConcurrentDictionary <string, int> txts = textService.GetAsConcurrent(id); log.Info("Datasetid " + id.ToString() + " -- Starting LoadRenPre(...)"); states = LoadRenPre(ds, repository, subs, tags, nums, txts); ManageErrors(states); log.Info(string.Format("Datasetid {0} -- Variables after LoadRenPre(..): ManageErrors: {1}; Reners: {2}/{3}; Presentations: {4}/{5}", id, ok, ds.ProcessedRenders, ds.TotalRenders, ds.ProcessedPresentations, ds.TotalPresentations)); ////END PROCESS ////////////////////////////////////////////////////////////////////////////////////////////////////////// subs.Clear(); subs = null; tags.Clear(); tags = null; nums.Clear(); nums = null; txts.Clear(); txts = null; GC.Collect();//force GC watch.Stop(); TimeSpan ts = watch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); log.Info("Datasetid " + id.ToString() + " -- END dataset process -- time: " + elapsedTime); } else { log.Fatal("Datasetid " + id.ToString() + " does not exists"); } } } catch (Exception ex) { log.Fatal("Datasetid " + id.ToString() + " -- Unexpected error in EdgarDatasetService.Run(" + id.ToString() + "): " + ex.Message, ex); log.FatalInner(ex.InnerException); } }); t.Start(); datasetsInProcess.TryAdd(id, t); }
/// <summary> /// 致命错误的日志 /// </summary> /// <param name="str"></param> public static void RecordingFatal(string str) { log.Fatal(str); }
public static void Fatal(object message) { Logger.Fatal(GetBefore() + message + GetAfter()); }
public void Fatal(string message) { log.Fatal(message); }
/// <summary> /// Run the Aggregator - Production Mode /// </summary> public void Run(RunMode rm) { try { if (rm == RunMode.NORMAL || rm == RunMode.TEST) { log.Info($"Starting Aggregator in Run Mode {rm}"); string AppConfig = dc.Config + ac.AppConfig; string ServerConfig = dc.Config + ac.ServerConfig; log.Debug("Configuration variables set"); #region Log Retention Module LogRetention logRetention = new LogRetention(); logRetention.Run(); #endregion #region Garbage Collector Module GarbageCollector garbageCollector = new GarbageCollector(); garbageCollector.Run(); #endregion #region Set Variables bool DataUpdateJobStatus = Convert.ToBoolean(Utilities.ReadXMLValue(AppConfig, "DataUpdateJobStatus")); log.Debug("DataUpdateJobStatus bool value set"); bool Office365AdobeImportTables = Convert.ToBoolean(Utilities.ReadXMLValue(AppConfig, "Office365AdobeImportTables")); log.Debug("Office365AdobeImportTables bool value set"); bool SRSImportDate = Convert.ToBoolean(Utilities.ReadXMLValue(AppConfig, "SRSImportDate")); log.Debug("SRSImportDate bool value set"); bool LogInterrogator = Convert.ToBoolean(Utilities.ReadXMLValue(AppConfig, "LogInterrogator")); log.Debug("LogInterrogator bool value set"); bool PlatformVersionCheck = Convert.ToBoolean(Utilities.ReadXMLValue(AppConfig, "PlatformVersionCheck")); log.Debug("PlatformVersionCheck bool value set"); bool LicenseManagerServices = Convert.ToBoolean(Utilities.ReadXMLValue(AppConfig, "LicenseManagerServices")); log.Debug("LicenseManagerServices bool value set"); bool LicenseManagerDeviceReporting = Convert.ToBoolean(Utilities.ReadXMLValue(AppConfig, "LicenseManagerDeviceReporting")); log.Debug("LicenseManagerDeviceReporting bool value set"); bool LicenseManagerStorage = Convert.ToBoolean(Utilities.ReadXMLValue(AppConfig, "LicenseManagerStorage")); log.Debug("LicenseManagerStorage bool value set"); bool InventoryServerServices = Convert.ToBoolean(Utilities.ReadXMLValue(AppConfig, "InventoryServerServices")); log.Debug("InventoryServerServices bool value set"); bool InventoryServerStorage = Convert.ToBoolean(Utilities.ReadXMLValue(AppConfig, "InventoryServerStorage")); log.Debug("InventoryServerStorage bool value set"); bool InventoryServerDeviceReporting = Convert.ToBoolean(Utilities.ReadXMLValue(AppConfig, "InventoryServerDeviceReporting")); log.Debug("InventoryServerDeviceReporting bool value set"); bool InventoryServerProcessing = Convert.ToBoolean(Utilities.ReadXMLValue(AppConfig, "InventoryServerProcessing")); log.Debug("InventoryServerProcessing bool value set"); string LicenseManagerServer = Utilities.ReadXMLValue(ServerConfig, "LicenseManager"); log.Debug("LicenseManagerServer string value set"); string InventoryServer = Utilities.ReadXMLValue(ServerConfig, "InventoryServer"); log.Debug("InventoryServer string value set"); log.Info("Configuration information has been loaded into memory"); #endregion DataRetriever dataRetriever = new DataRetriever(); log.Info("Data Retriever has been initialized"); #region Exporters log.Info("This might take a while, be paitent..."); Console.WriteLine("This might take a while, be paitent..."); // DUJ Status try { if (DataUpdateJobStatus) { if (dataRetriever.GetDataUpdateJob()) { log.Info("Data Update Job information exported"); Console.WriteLine("Data Update Job information exported"); } } } catch (Exception ex) { log.Error(ex); } // License Manager Services try { if (LicenseManagerServices) { if (dataRetriever.GetWindowsServices("License Manager", LicenseManagerServer)) { log.Info("Windows Services information exported for LicenseManager"); Console.WriteLine("Windows Services information exported for LicenseManager"); } } } catch (Exception ex) { log.Error(ex); } // Inventory Service Services try { if (InventoryServerServices) { if (dataRetriever.GetWindowsServices("Inventory Server", InventoryServer)) { log.Info("Windows Services information exported for InventoryServer"); Console.WriteLine("Windows Services information exported for InventoryServer"); } } } catch (Exception ex) { log.Error(ex); } // Inventory Server Storage try { if (InventoryServerStorage) { if (dataRetriever.GetWindowsStorage("Inventory Server", InventoryServer)) { log.Info("Windows Storage information exported for InventoryServer"); Console.WriteLine("Windows Storage information exported for InventoryServer"); } } } catch (Exception ex) { log.Error(ex); } // License Manager Storage try { if (LicenseManagerStorage) { if (dataRetriever.GetWindowsStorage("License Manager", LicenseManagerServer)) { log.Info("Windows Storage information exported for LicenseManager"); Console.WriteLine("Windows Storage information exported for LicenseManager"); } } } catch (Exception ex) { log.Error(ex); } // Office365 Adobe Import Tables try { if (Office365AdobeImportTables) { if (dataRetriever.GetConnectorImportTables()) { log.Info("Office 365 and Adobe Import tables exported"); Console.WriteLine("Office 365 and Adobe Import tables exported"); } } } catch (Exception ex) { log.Error(ex); } // Log Interrogator try { if (LogInterrogator) { if (dataRetriever.GetSnowLogHealth()) { log.Info("Snow Log Health exported"); Console.WriteLine("Snow Log Health exported"); } } } catch (Exception ex) { log.Error(ex); } // Platform Version Check try { if (PlatformVersionCheck) { if (dataRetriever.GetProductVersions()) { log.Info("Product Versions exported"); Console.WriteLine("Product Versions exported"); } } } catch (Exception ex) { log.Error(ex); } // License Manager Device Reporting try { if (LicenseManagerDeviceReporting) { if (dataRetriever.GetReportedToday(slm: true)) { log.Info("LicenseManager Device Reporting exported"); Console.WriteLine("LicenseManager Device Reporting exported"); } } } catch (Exception ex) { log.Error(ex); } // Inventory Server Device Reporting try { if (InventoryServerDeviceReporting) { if (dataRetriever.GetReportedToday(sinv: true)) { log.Info("SnowInventory Device Reporting exported"); Console.WriteLine("SnowInventory Device Reporting exported"); } } } catch (Exception ex) { log.Error(ex); } // SRS Import Date and Inventory Server Processing try { if (SRSImportDate == true || InventoryServerProcessing == true) { if (dataRetriever.GetExtras(SRSImportDate, InventoryServerProcessing)) { log.Info("GetExtras exported"); Console.WriteLine("GetExtras exported"); } } } catch (Exception ex) { log.Error(ex); } #endregion #region Mailer Mailer m = new Mailer(); string filename = dc.Export + dataRetriever.ExportName; log.Info($"New mailer initialized in Run Mode {rm}"); Console.WriteLine($"New mailer initialized in Run Mode {rm}"); if (rm == RunMode.NORMAL) { m.SendEmail(filename, Assembly.GetExecutingAssembly().GetName().Version.ToString()); } else if (rm == RunMode.TEST) { m.SendEmail(filename, Assembly.GetExecutingAssembly().GetName().Version.ToString(), "TEST"); } log.Debug("Email command sent"); #endregion log.Info($"Aggregation finished"); Console.WriteLine($"Aggregation finished"); } } catch (Exception ex) { log.Fatal(ex); Mailer m = new Mailer(); m.SendFailureAlert("Failure to export" + Environment.NewLine + ex.Message + ex.StackTrace + Environment.NewLine + " Please investigate!"); } }
public void Log(LogEntry entry) { // Need to get the calling method's type when instantiating an ILog object. var method = new StackFrame(1).GetMethod(); var type = method.DeclaringType; log4net.ILog log = log4net.LogManager.GetLogger(type); switch (entry.Severity) { case LogLevel.Debug: if (entry.Exception == null) { log.Debug(entry.Message); } else { log.Debug(entry.Message, entry.Exception); } break; case LogLevel.Information: if (entry.Exception == null) { log.Info(entry.Message); } else { log.Info(entry.Message, entry.Exception); } break; case LogLevel.Warning: if (entry.Exception == null) { log.Warn(entry.Message); } else { log.Warn(entry.Message, entry.Exception); } break; case LogLevel.Error: if (entry.Exception == null) { log.Error(entry.Message); } else { log.Error(entry.Message, entry.Exception); } break; case LogLevel.Fatal: if (entry.Exception == null) { log.Fatal(entry.Message); } else { log.Fatal(entry.Message, entry.Exception); } break; default: if (entry.Exception == null) { log.Info(entry.Message); } else { log.Info(entry.Message, entry.Exception); } break; } }
/// <summary> /// Unhandled Exception Handler /// </summary> private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { log.Fatal("Unhandled Exception --", (Exception)e.ExceptionObject); Environment.Exit(ERROR_RESULT); }
static void app_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { logger.Fatal(e.Exception.Message); logger.Fatal(e.Exception.StackTrace); }
public static void Exception(Exception ex) => _error.Fatal(ex.ToString());
protected void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs log4net.ILog logger = log4net.LogManager.GetLogger(GetType()); logger.Fatal(Server.GetLastError()); }
public static void LogFatal(Exception ex) { log.Fatal(ex); }
public static void WriteFatal(Exception ex) { log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); log.Fatal("严重错误", ex); }
public void LogCritical(string strMessage) { log.Fatal(strMessage); }
public void Fatal(Exception error, string format, params object[] args) { _loger.Fatal(Format(format, args), error); }
static int Main(string[] args) { //Console.WriteLine("Press Enter to continue"); //Console.Read(); _log.Info("App started"); var options = new Options(); var parser_options = new CommandLine.ParserSettings { MutuallyExclusive = true }; var parser = new CommandLine.Parser(parser_options); var isValid = parser.ParseArguments(args, options); if (!isValid) { Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(options).ToString()); return(-1); } // Don't allow lower case serial options.SMT_Serial = options.SMT_Serial.ToUpper(); Console.WriteLine("SMT Serial: " + options.SMT_Serial); Console.WriteLine("Host: " + options.Host); Console.WriteLine(); // Check board was passed diags try { using (CLStoreEntities cx = new CLStoreEntities()) { LowesHub h = cx.LowesHubs.Where(lh => lh.smt_serial == options.SMT_Serial).OrderByDescending(lh => lh.date).First(); string info = string.Format("Hub {0} last diags {1}", h.MacAddress.MAC.ToString("X"), h.date.ToString()); _log.Info(info); } } catch (Exception ex) { _log.Fatal("Problem retrieving Hub diag info\r\n\r\n" + ex.Message + "\r\n" + ex.StackTrace); return(-3); } if (options.CalibrateLEDs) { BatteryTest batcal = new BatteryTest(options.Host, options.SMT_Serial); char save_option = 'n'; while (true) { Console.WriteLine("Getting LEDs values...\r\n"); double[] values = batcal.GetLEDsValues(); int i = 0; Console.WriteLine("Red On : {0}", values[i++].ToString("G2")); Console.WriteLine("Green On : {0}", values[i++].ToString("G2")); Console.WriteLine("Yellow On: {0}", values[i++].ToString("G2")); Console.WriteLine(); Console.WriteLine("Red Off : {0}", values[i++].ToString("G2")); Console.WriteLine("Green Off : {0}", values[i++].ToString("G2")); Console.WriteLine("Yellow Off: {0}", values[i++].ToString("G2")); i = 0; Properties.Settings.Default.LED_Red_On_Val = values[i++]; Properties.Settings.Default.LED_Green_On_Val = values[i++]; Properties.Settings.Default.LED_Yellow_On_Val = values[i++]; Properties.Settings.Default.LED_Red_Off_Val = values[i++]; Properties.Settings.Default.LED_Green_Off_Val = values[i++]; Properties.Settings.Default.LED_Yellow_Off_Val = values[i++]; Console.WriteLine("Save Values? (y/n/r):"); save_option = Convert.ToChar(Console.Read()); if (save_option != 'r') { break; } } if (save_option == 'y') { Properties.Settings.Default.Save(); } } try { if (!options.NoJigMode) { BatteryTest battery_test = new BatteryTest(options.Host, options.SMT_Serial); battery_test.InvalidateEnabled = !options.DisableInvalidate; battery_test.Status_Event += Battery_test_Status_Event; battery_test.LogFolder = Properties.Settings.Default.Log_Folder; Directory.CreateDirectory(battery_test.LogFolder); battery_test.LED_Red.OnVal = Properties.Settings.Default.LED_Red_On_Val; battery_test.LED_Red.OffVal = Properties.Settings.Default.LED_Red_Off_Val; battery_test.LED_Green.OnVal = Properties.Settings.Default.LED_Green_On_Val; battery_test.LED_Green.OffVal = Properties.Settings.Default.LED_Green_Off_Val; battery_test.LED_Yellow.OnVal = Properties.Settings.Default.LED_Yellow_On_Val; battery_test.LED_Yellow.OffVal = Properties.Settings.Default.LED_Yellow_Off_Val; battery_test.Run(); } else { BatteryTestNoJig batery_test = new BatteryTestNoJig(options.Host, options.SMT_Serial); batery_test.InvalidateEnabled = !options.DisableInvalidate; batery_test.Status_Event += Baterytest_Status_Event; batery_test.LogFolder = Properties.Settings.Default.Log_Folder; Directory.CreateDirectory(batery_test.LogFolder); batery_test.Run(); } } catch (Exception ex) { _log.Fatal(ex.Message + "\r\n" + ex.StackTrace); return(-2); } finally { if (!options.NoJigMode) { BatteryJig.Set_all_relays(false); } } _log.Info("All Tests Passed"); if (!options.PrintLabelDisabled) { _log.Info("Printing label..."); try { DataUtils.PrintHubLabel( options.SMT_Serial, Properties.Settings.Default.ZPL_Lable_File, Properties.Settings.Default.Printer_Address); } catch (Exception ex) { _log.Fatal(ex.Message + "\r\n" + ex.StackTrace); return(-2); } finally { } } return(0); }
public void Fatal(object message) { _log.Fatal(message); }
public static void LogFatal(object ex) { log.Fatal(ex); }
public void Fatal(object message) { _log4NetLogger.Fatal(message); }
/// <summary> /// 严重警告信息 /// </summary> /// <param name="info">错误信息</param> public static void LogFatal(string info) { logger.Fatal(info); }
public static DataSet GetDataSet() { DataSet dataset = new DataSet("applicationDataSet"); // Create Table Properties DataTable properties = new DataTable("Properties"); DataColumn propertyId = new DataColumn("propertyId", typeof(Int32)); properties.Columns.Add(propertyId); DataColumn parentCategory = new DataColumn("parentCategory", typeof(string)); properties.Columns.Add(parentCategory); DataColumn category = new DataColumn("category", typeof(string)); properties.Columns.Add(category); DataColumn propertyName = new DataColumn("propertyName", typeof(string)); properties.Columns.Add(propertyName); dataset.Tables.Add(properties); // Create Table PropertyValues DataTable propertyValues = new DataTable("PropertyValues"); DataColumn propertyId_1 = new DataColumn("propertyId", typeof(Int32)); propertyValues.Columns.Add(propertyId_1); DataColumn propertyValue = new DataColumn("propertyValue", typeof(string)); propertyValues.Columns.Add(propertyValue); DataColumn rowStatus = new DataColumn("rowStatus", typeof(Int32)); rowStatus.DefaultValue = 0; propertyValues.Columns.Add(rowStatus); dataset.Tables.Add(propertyValues); using (OleDbConnection connection = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False", dbPath))) { OleDbDataAdapter propertiesAdapter = new OleDbDataAdapter("SELECT * FROM Properties", connection); OleDbDataAdapter propertyValuesAdapter = new OleDbDataAdapter("SELECT * FROM PropertyValues", connection); try { log.Info("GetDataSet:: opening connection"); connection.Open(); log.Info("GetDataSet:: Success: connection opened!"); propertiesAdapter.Fill(dataset, "Properties"); propertyValuesAdapter.Fill(dataset, "PropertyValues"); log.Info("GetDataSet:: adapters are filled"); DataRelation relation = dataset.Relations.Add("fk_relation", dataset.Tables["Properties"].Columns["propertyId"], dataset.Tables["PropertyValues"].Columns["propertyId"]); log.Info("GetDataSet:: foreign key relation created!"); } catch (Exception exception) { log.Fatal("GetDataSet:: ", exception); } } return(dataset); }
/// <summary> /// 输出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="ex"></param> #region static void Fatal(Type t, Exception ex) public static void Fatal(Type t, Exception ex) { log4net.ILog log = log4net.LogManager.GetLogger(t.Name); log.Fatal("Fatal", ex); }