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()); }; }
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); }
/// <summary> /// Commits the offsets of all messages consumed so far. /// </summary> public void CommitOffsets() { this.EnsuresNotDisposed(); if (this.GetZkClient() == null) { return; } try { foreach (KeyValuePair <string, IDictionary <int, PartitionTopicInfo> > topic in topicRegistry) { var topicDirs = new ZKGroupTopicDirs(this.config.GroupId, topic.Key); foreach (KeyValuePair <int, PartitionTopicInfo> partition in topic.Value) { var newOffset = partition.Value.ConsumeOffset; try { if (partition.Value.ConsumeOffsetValid) { // Save offsets unconditionally. Kafka's latestOffset for a particular topic-partition can go backward // if a follwer which is not fully caught up becomes a leader. We still need to save the conumed offsets even then. //skip only if we are trying to commit the same offset if (newOffset != partition.Value.CommitedOffset) { try { ZkUtils.UpdatePersistentPath(GetZkClient(), topicDirs.ConsumerOffsetDir + "/" + partition.Value.PartitionId, newOffset.ToString()); partition.Value.CommitedOffset = newOffset; } catch (Exception ex) { Logger.ErrorFormat("error in CommitOffsets UpdatePersistentPath : {0}", ex.FormatException()); } } } else { Logger.InfoFormat("Skip committing offset {0} for topic {1} because it is invalid (ZK session is disconnected)", newOffset, partition); } } catch (Exception ex) { Logger.WarnFormat("exception during CommitOffsets: {0}", ex.FormatException()); } if (Logger.IsDebugEnabled) { Logger.DebugFormat("Commited offset {0} for topic {1}", newOffset, partition); } } } } catch (Exception ex) { Logger.ErrorFormat("error in CommitOffsets : {0}", ex.FormatException()); } }
public virtual void OnMessage(QuickFix.FIX44.ApplicationMessageRequestAck message, SessionID session) { try { string[] quebraApplReqID = message.ApplReqID.ToString().Split("|".ToCharArray()); string applReqID = quebraApplReqID[0]; string sessionIDResponse = quebraApplReqID[1]; // Retorna o applReqID original message.Set(new QuickFix.Fields.ApplReqID(quebraApplReqID[0])); // Inverte origem e destino da mensagem, para devolver a resposta ao cliente Fix message.Header.SetField(new QuickFix.Fields.SenderCompID(_dctSessionsFixClients[sessionIDResponse].TargetCompID)); message.Header.SetField(new QuickFix.Fields.SenderSubID(_dctSessionsFixClients[sessionIDResponse].TargetSubID)); message.Header.SetField(new QuickFix.Fields.TargetCompID(_dctSessionsFixClients[sessionIDResponse].SenderCompID)); message.Header.SetField(new QuickFix.Fields.TargetSubID(_dctSessionsFixClients[sessionIDResponse].SenderSubID)); logger.InfoFormat("SessionID[{0}]: ApplicationMessageRequestAck enviando para sessionIDResponse[{1}] msg[{2}]", session.ToString(), sessionIDResponse, message.ToString()); bool bRet = Session.SendToTarget(message, _dctSessionsFixClients[sessionIDResponse]); if (!bRet) { logger.ErrorFormat("SessionID[{0}]: Falha ApplicationMessageRequestAck sessionIDResponse[{1}] msg[{2}]", session.ToString(), sessionIDResponse, message.ToString()); } } catch (Exception ex) { logger.Error("onMessage(ApplicationMessageRequestAck): " + ex.Message, ex); } }
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); } }
public void Initialise(Scene scene, IConfigSource source) { string databaseDir = "./"; string database = "FileSystemDatabase"; int channel = 345; try { if (source.Configs["CMS"] == null) { return; } m_enabled = source.Configs["CMS"].GetBoolean("enabled", false); databaseDir = source.Configs["CMS"].GetString("directory", databaseDir); database = source.Configs["CMS"].GetString("database", database); channel = source.Configs["CMS"].GetInt("channel", channel); if (database != "FileSystemDatabase" && database != "GitDatabase") { m_log.ErrorFormat("[Content Management]: The Database attribute must be defined as either FileSystemDatabase or GitDatabase"); m_enabled = false; } } catch (Exception e) { m_log.ErrorFormat("[Content Management]: Exception thrown while reading parameters from configuration file. Message: " + e); m_enabled = false; } if (!m_enabled) { m_log.Info("[Content Management]: Content Management System is not Enabled."); return; } lock (this) { if (!initialised) //only init once { m_view = new CMView(); m_model = new CMModel(); m_control = new CMController(m_model, m_view, scene, channel); m_model.Initialise(database); m_view.Initialise(m_model); initialised = true; m_model.InitialiseDatabase(scene, databaseDir); } else { m_model.InitialiseDatabase(scene, databaseDir); m_control.RegisterNewRegion(scene); } } }
/// <summary> /// /// </summary> /// <param name="index"></param> /// <param name="dataGridViewRow"></param> /// <returns></returns> public int InsertAt(int index, OfferBookGridRow dataGridViewRow) { int _ret = 0; try { if (this.grouped) { int pos; //lock (this.Rows) lock (syncRoot) { pos = ValidatePosition(index, ref dataGridViewRow); if (pos > 0) { this.Rows.Insert(pos, dataGridViewRow); } else { this.Rows.Insert(1, dataGridViewRow); } _ret = pos; } } else { //Workaround: the broadcasting service is sending the signal even after the cancellation. //We must make sure that the list is empty after cancellation if (index <= this.Rows.Count + 1) { //lock (this.Rows) lock (syncRoot) { this.Rows.Insert(index, dataGridViewRow); _ret = index; } } } } catch (ArgumentOutOfRangeException outOfRangeEx) { logger.Warn(String.Format("OfferBookGrid > InsertAt({0}): a posição {1} de {2} do livro (Agrupado:{3}) não existe mais ({4}).", this.Stock, index, this.RowCount, this.grouped, outOfRangeEx.Message)); } catch (Exception ex) { //AplicacaoGeral.ReportarErro("OfferBookGrid > InsertAt", ex + " | " + index.ToString() + " | " + this.RowCount.ToString() + " | " + this.grouped.ToString()); logger.ErrorFormat("Exception [{0}] [{1}] [{2}] [{3}]", ex, index, this.RowCount, this.grouped); } return(_ret); }
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Exception ex = e.ExceptionObject as Exception; if (ex != null) { logger.ErrorFormat("terminate:{0}; error:{1}", e.IsTerminating, ex.ToString()); } else { logger.ErrorFormat("terminate:{0}; ", e.IsTerminating); } }
public void CheckRetCode(FMOD.RESULT result) { if (result != FMOD.RESULT.OK) { if (result == FMOD.RESULT.ERR_INVALID_HANDLE) { log.WarnFormat("Invalid Sound Handle\n{0}", new StackTrace(true).ToString()); } else { log.ErrorFormat("FMOD result: {0}\n{1}", FMOD.Error.String(result), new StackTrace(true).ToString()); //throw new FMODException("Fmod error: ", result); } } }
// This function computes the level of detail(meters per sample) that a tile should use, based // on the tiles location (distance from the camera). Eventually this might be a delegate supplied // by the application to allow for more flexible configuration. public override int MetersPerSample(Vector3 tileLoc, int pagesFromCamera, int subPagesFromCamera) { int ret; switch (pagesFromCamera) { case 0: ret = 8; break; case 1: ret = 8; break; case 2: ret = 8; break; case 3: ret = 8; break; case 4: ret = 8; break; default: log.ErrorFormat("MetersPerSample out of range at {0} pages", pagesFromCamera); // Debug.Assert(false, "MetersPerSample: out of range"); ret = 8; break; } return(ret); }
internal static bool TryParsePartitionLeader(string partitionState, out int leader) { leader = Int32.MinValue; bool success = true; try { // Parse leader value from partition state JSON string var ser = new JavaScriptSerializer(); Dictionary <string, object> result = ser.Deserialize <Dictionary <string, object> >(partitionState); leader = (int)result["leader"]; } catch (Exception ex) { Logger.Error("Failed to parse partition leader due to the following exception: " + ex.Message); success = false; } if (leader == Int32.MinValue) { Logger.ErrorFormat("Can't get leader from zookeeper data: {0}", partitionState); return(false); } return(success); }
static void Main( ) { // Log file setup log.InfoFormat("\n"); log.InfoFormat("SCJMapper_V2 - Started"); CultureInfo current = CultureInfo.CurrentCulture; CultureInfo modded = new CultureInfo(current.Name); // that is the users locale log.InfoFormat("SCJMapper_V2 - using current culture : {0}", modded.Name); if (!string.IsNullOrEmpty(AppConfiguration.AppConfig.culture)) { try { modded = new CultureInfo(AppConfiguration.AppConfig.culture); // that is the users locale log.InfoFormat("SCJMapper_V2 - override culture from config file: {0}", modded.Name); } catch { log.ErrorFormat("SCJMapper_V2 - Error in culture name from config file: {0}", AppConfiguration.AppConfig.culture); } } CultureInfo us = new CultureInfo("en-US"); modded.NumberFormat = us.NumberFormat; // change the whole number format to US - should be safe ... // change the applications formatting to US (the dec point is essential here) SetDefaultCulture(modded); // have to maintain number formats without tracking every piece of code with locales log.InfoFormat("SCJMapper_V2 - Changed to US number formatting"); Application.EnableVisualStyles( ); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm( )); log.InfoFormat("SCJMapper_V2 - Ended\n"); }
public static void error(string format, params object[] args) { if (logerror.IsErrorEnabled) { logerror.ErrorFormat(format, args); } }
public virtual void OnMessage(QuickFix.FIX44.ApplicationMessageRequest message, SessionID session) { try { string sessionID = session.ToString(); string applReqID = message.ApplReqID.ToString(); logger.InfoFormat("SessionID[{0}]: ApplicationMessageRequest ApplReqID[{1}]", sessionID, applReqID); // Acrescenta o sessionID do cliente para controle applReqID = applReqID + "|" + sessionID; message.Set(new QuickFix.Fields.ApplReqID(applReqID)); string[] quebraApplReqID = applReqID.Split("-".ToCharArray()); string channelID = quebraApplReqID[1]; logger.DebugFormat("SessionID[{0}]: ApplicationMessageRequest enviando para ChannelID[{1}] msg[{2}]", sessionID, channelID, message.ToString()); bool bRet = Session.SendToTarget(message, _dctSessionsFixChannels[channelID]); if (!bRet) { logger.ErrorFormat("SessionID[{0}]: Falha ApplicationMessageRequest msg[{1}]", sessionID, message.ToString()); } } catch (Exception ex) { logger.Error("onMessage(ApplicationMessageRequest): " + ex.Message, ex); } }
public void ErrorFormat(string format, params object[] args) { if (IsErrorEnabled) { log.ErrorFormat(format, args); } }
/// <summary> /// 输出普通日志 /// </summary> /// <param name="level"></param> /// <param name="format"></param> /// <param name="args"></param> private void Log(LoggerLevel level, string format, params object[] args) { switch (level) { case LoggerLevel.Debug: _Logger4net.DebugFormat(format, args); break; case LoggerLevel.Info: _Logger4net.InfoFormat(format, args); break; case LoggerLevel.Warn: _Logger4net.WarnFormat(format, args); break; case LoggerLevel.Error: _Logger4net.ErrorFormat(format, args); break; case LoggerLevel.Fatal: _Logger4net.FatalFormat(format, args); break; } }
/// <summary> /// 错误 /// </summary> public static void ErrorFormat(string message, params object[] args) { if (log.IsErrorEnabled) { log.ErrorFormat(message, args); } }
/// <summary> /// Criar os diretorios caso nao existam /// </summary> /// <param name="lst"></param> /// <returns></returns> public bool CreatePaths() { bool ret = true; List <String> lst = new List <string>(); lst.Add(this.Config.PathWatcher); lst.Add(this.Config.PathBkp); lst.Add(this.Config.PathProcessed); foreach (string path in lst) { try { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } catch (Exception ex) { logger.ErrorFormat("Problemas na criacao do diretorio: [{0}] Msg:[{1}]", path, ex.StackTrace + " " + ex.Message); ret = false; } } return(ret); }
public int Build(bool stencilShadows, bool logDetails) { int bucketCount = 0; if (logDetails) { log.InfoFormat("MaterialBucket.Build: Building material {0}", materialName); } material = MaterialManager.Instance.GetByName(materialName); if (material == null) { log.ErrorFormat("MaterialBucket.Build: Could not find material {0}", materialName); } else { material.Load(); // tell the geometry buckets to build foreach (GeometryBucket gbucket in geometryBucketList) { gbucket.Build(stencilShadows, logDetails); bucketCount++; } } return(bucketCount); }
//認証 正常:0 異常:-1 public int getOpeAuth(String userid, string pass, NpgsqlConnection conn) { NpgsqlCommand cmd; try { int ret = 0; if (conn.FullState != ConnectionState.Open) { conn.Open(); } String sql = @"SELECT openo,opeid,lastname,fastname,type FROM ope WHERE opeid = :opeid AND password=:pass "; cmd = new NpgsqlCommand(sql, conn); cmd.Parameters.Add(new NpgsqlParameter("opeid", DbType.String) { Value = m_opeid.Text }); cmd.Parameters.Add(new NpgsqlParameter("pass", DbType.String) { Value = m_pass.Text }); opeData = new opeDS(); int i = 0; var dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { opeData.openo = dataReader["openo"].ToString(); opeData.opeid = dataReader["opeid"].ToString(); opeData.lastname = dataReader["lastname"].ToString(); opeData.fastname = dataReader["fastname"].ToString(); opeData.type = dataReader["type"].ToString(); i++; } //取得できない場合はエラー if (i <= 0) { MessageBox.Show("ログインに失敗しました。", "ログイン", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); logger.InfoFormat("ログインに失敗しました: User -> {0}", m_opeid.Text); ret = -1; } else if (i > 0) { ret = 0; } return(ret); } catch (Exception ex) { MessageBox.Show("オペレータ情報の取得に失敗しました。" + ex.Message, "オペレータ情報取得", MessageBoxButtons.OK, MessageBoxIcon.Error); logger.ErrorFormat("オペレータ情報の取得に失敗しました MSG: {0}: User -> {1}, pass -> {2}", ex.Message, m_opeid.Text, m_pass.Text); return(-1); } }
public static void logError(string format, params object[] args) { Console.WriteLine(format, args); if (initLog4net()) { logger.ErrorFormat(format, args); } }
public void Start() { if (!SetConfig("Started")) { log.ErrorFormat("Missing config: " + errs.ToString()); stopSignaled = true; return; } stopSignaled = false; watcher = new FileSystemWatcher(); watcher.Path = config.listenPath; watcher.Filter = config.listenFilter; watcher.IncludeSubdirectories = false; watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); watcher.Deleted += new FileSystemEventHandler(OnChanged); watcher.Renamed += new RenamedEventHandler(OnRenamed); timer1 = new System.Timers.Timer(); timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed); timer1.Interval = config.timerInterval; //Good to go timer1.Enabled = true; watcher.EnableRaisingEvents = true; DoProcess(); }
public static void Error(ILog log, string format, params object[] @params) { if (log == null) { return; } log.ErrorFormat(format, @params); }
static void Main(string[] args) { //initialize logging var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); log4net.Config.XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); Console.WriteLine("Hello World!"); log.Info("Email Sent"); EmailHelper mail = new EmailHelper(); mail.sendMail("Email Subject", "Email Body"); using (SqlConnection connection = dbHelper.createWFConfigDBConn()) { try { Console.WriteLine("\nQuery data example:"); Console.WriteLine("=========================================\n"); connection.Open(); String sql = "SELECT TOP 20 prjCode,prjName from tbProject"; using (SqlCommand command = new SqlCommand(sql, connection)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1)); } } } } catch (SqlException e) { Console.WriteLine(e.ToString()); log.ErrorFormat("Error query to database : {0}", e.ToString()); } finally { connection.Close(); } } Console.Write("Masukkan username : "******"DeptHead : {0} {1} {2}", deptHead.fullName, deptHead.email, deptHead.userName); Console.WriteLine("BUHead : {0} {1} {2}", BUHead.fullName, BUHead.email, BUHead.userName); Console.ReadLine(); }
/// <summary> /// 抛出异常时,记录程序无法处理的异常信息 /// 已经try catch处理过的,不进入该流程 /// </summary> /// <param name="args"></param> public override void OnException(MethodExecutionArgs args) { string expMsg = string.Format("!!! Exception [{0}] {1} {2}", _hashCode, _methodName, args.Exception.ToString()); _logger.ErrorFormat(expMsg, args.Exception); //重定向到指定的错误页面 string errorurl = "/Error/Index"; System.Web.HttpContext.Current.Response.Redirect(errorurl); }
public Request(string url, string textureName, TextureFetchDone doneHandler, int destWidth, int destHeight, bool keepAspect, ColorEx fillColor, string authUser, string authPW, string authDomain) { this.url = url; if (!url.StartsWith("http:")) { log.ErrorFormat("TextureFetch: only http urls supported: {0}", url); throw new Exception("TextureFetch: only http urls supported: " + url); } this.textureName = textureName; this.doneHandler = doneHandler; this.destWidth = destWidth; this.destHeight = destHeight; this.keepAspect = keepAspect; this.fillColor = fillColor; this.authUser = authUser; this.authPW = authPW; this.authDomain = authDomain; }
public static void WriteException(Exception ex, params object[] arrVal) { var msgException = ex.Message; var exceptionLogUid = Guid.NewGuid(); var innerException = GetInternalErrors(ex); var paramsValues = GetSerializedValues(arrVal); var stackTrace = ex.StackTrace; Log.ErrorFormat("Uid: {0} | Msg: {1} | InExc: {2} | Params: {3} | St: {4}", exceptionLogUid, msgException, innerException, paramsValues, stackTrace); }
/// <summary> /// Constructor /// </summary> /// <param name="model">MSSQLAuditor model</param> public WebServerManager(MsSqlAuditorModel model) { int tryCount = 10; bool webServerStarted = false; Random rnd = new Random(); this._model = model; _webServerPort = Consts.DefaultWebServerPort; for (int i = 0; i < tryCount; i++) { try { this._frontend = new WebServerFrontend(_webServerPort, ProcessRequest); log.InfoFormat("Web-server started at port:'{0}'", _webServerPort ); webServerStarted = true; break; } catch (Exception ex) { log.ErrorFormat("Unable to start web-server at port:'{0}'.Error:'{1}'", _webServerPort, ex ); } _webServerPort = 10000 + rnd.Next(50000); } if (!webServerStarted) { log.ErrorFormat( "Unable to start web-server for '{0}' times", tryCount ); } }
/// <summary> /// Check instances updates from sqlite /// </summary> public void CheckUpdates() { string strReturnMessage = string.Empty; if (!IsInitialized()) { log.ErrorFormat( @"Storage is not initialized" ); } else { LoadFromDB(false); } log.DebugFormat( @"Active scheduled Instances:'{0}' Active schedules: '{1}'", _serviceNodeInstances.Count, _serviceSchedules.Count ); }
private bool False(string msg, string logMsg = null) { StackFrame frame = new StackFrame(1); var method = frame.GetMethod(); var type = method.DeclaringType; var name = method.Name; log.ErrorFormat(name + ": " + logMsg == null ? msg : logMsg); errMsg = msg; return(false); }
public override void initialize() { List <EntityBase> objs = m_scene.GetEntities(); lock (objs) { try { foreach (EntityBase obj in objs) { if (obj is SceneObjectGroup) { SceneObjectGroup mapdot = (SceneObjectGroup)obj; foreach (SceneObjectPart part in mapdot.Children.Values) { if (part == null) { continue; } LLVector3CL position = Utility.toLLVector3(part.GroupPosition); LLQuaternionCL rotation = Utility.toLLQuaternion(part.RotationOffset); LLVector3CL scale = Utility.toLLVector3(part.Scale); PrimitiveBaseShape shape = part.Shape; LLPathParamsCL pathParams = new LLPathParamsCL(shape.PathCurve, shape.PathBegin, shape.PathEnd, shape.PathScaleX, shape.PathScaleY, shape.PathShearX, shape.PathShearY, shape.PathTwist, shape.PathTwistBegin, shape.PathRadiusOffset, shape.PathTaperX, shape.PathTaperY, shape.PathRevolutions, shape.PathSkew); LLProfileParamsCL profileParams = new LLProfileParamsCL(shape.ProfileCurve, shape.ProfileBegin, shape.ProfileEnd, shape.ProfileHollow); LLVolumeParamsCL volumeParams = new LLVolumeParamsCL(profileParams, pathParams); int facenum = part.GetNumberOfSides(); List <SimpleColorCL> colors = new List <SimpleColorCL>(); for (uint j = 0; j < facenum; j++) { TextureColorModel data = Utility.GetDataFromFile(shape.Textures.GetFace(j).TextureID.ToString()); colors.Add(new SimpleColorCL(data.A, data.R, data.G, data.B)); } m_primitiveList.Add(new PrimitiveCL(volumeParams, position, rotation, scale, colors.ToArray(), facenum)); } } } } catch (Exception e) { m_log.ErrorFormat("[WebMapService]: Initialize object layer failed with {0} {1}", e.Message, e.StackTrace); } } }
/// <summary> /// Get localized item /// </summary> /// <param name="locale">Language (null for default)</param> /// <returns></returns> public TemplateNodeLocaleInfo GetLocale(bool throwExceptionIfNotFound, string locale = null) { var targetLanguage = locale ?? this._model.Settings.InterfaceLanguage; var localized = Locales.FirstOrDefault(l => l.Language == targetLanguage); if (localized == null && throwExceptionIfNotFound) { log.ErrorFormat( "Localized item not found. TemplateNode.Name:'{0}';Language:'{1}'", PathAsString, targetLanguage ); throw new InvalidOperationException( "Localized item not found. TemplateNode.Name=" + PathAsString + " Language=" + targetLanguage ); } return(localized); }
public static Person getManager(string userName, int positionLevel) { Person retVal = new Person(); var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); log4net.Config.XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); using (SqlConnection connection = dbHelper.createMIPDBConn()) { try { connection.Open(); String sql = "[SPU_MIS_GetManagerByPositionLevel]"; String sqlEmail = "select Email from VU_EmployeeMAC where LoginName = @LoginName "; using (SqlCommand command = new SqlCommand(sql, connection)) { command.CommandType = System.Data.CommandType.StoredProcedure; command.Parameters.AddWithValue("iUserLogin", userName); command.Parameters.AddWithValue("iPositionLevel", positionLevel); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { retVal.userName = reader.GetString(2); retVal.fullName = reader.GetString(1); } } } using (SqlCommand command = new SqlCommand(sqlEmail, connection)) { command.Parameters.AddWithValue("LoginName", retVal.userName); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { retVal.email = reader.GetString(0); } } } } catch (SqlException e) { Console.WriteLine(e.ToString()); log.ErrorFormat("Error query to database : {0}", e.ToString()); } finally { connection.Close(); } } return(retVal); }
/// <summary> /// Log4Net错误记录封装 2014-08-28 14:58:50 By 唐有炜 /// </summary> /// <param name="message"></param> /// <param name="ex"></param> /// <returns></returns> public static void Error(string message, Exception ex) { if (logerror.IsErrorEnabled) { if (!string.IsNullOrEmpty(message) && ex == null) { logerror.ErrorFormat("<br/>【附加信息】 : {0}<br>", new object[] { message }); } else if (!string.IsNullOrEmpty(message) && ex != null) { string errorMsg = BeautyErrorMsg(ex); logerror.ErrorFormat("<br/>【附加信息】 : {0}<br>{1}", new object[] { message, errorMsg }); } else if (string.IsNullOrEmpty(message) && ex != null) { string errorMsg = BeautyErrorMsg(ex); logerror.Error(errorMsg); } } }
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); } }
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; }
/// <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 ); }
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(); } } }
/// <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); }
public virtual void ToLog(ILog log) { // Remove password from logging var safeConnectionString = new SqlConnectionStringBuilder(ConnectionString); if (!string.IsNullOrEmpty(safeConnectionString.Password)) { safeConnectionString.Password = "******"; } 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("=================================================="); } }
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); }
public static void LoggingError(ILog logger, string format, params object[] args) { logger.ErrorFormat(format, args); // logger.DebugFormat("ERROR: {0}::{1}()", method.DeclaringType, method.Name); }
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(); } }
/// <summary> /// Logs a formatted message string with the <see cref="F:log4net.Core.Level.Error"/> level. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> that supplies culture-specific formatting information</param> /// <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> /// <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(IFormatProvider provider, string format, object[] args, ILog log) { log.ErrorFormat(provider, format, args); }
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; }
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); } }
/// <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="arg0">An Object to format</param> /// <param name="log">The log.</param> /// <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,System.Exception)"/> /// methods instead. /// </para> /// </remarks> /// <seealso cref="M:log4net.ILog.Error(System.Object)"/> /// <seealso cref="P:log4net.ILog.IsErrorEnabled"/> public static void ErrorFormat(string format, object arg0, ILog log) { log.ErrorFormat(format, arg0); }