Example #1
0
        private static string GetConfigName(LogBase log)
        {
            void PrintConfigName(LogBase logP, string configNameP)
            {
                logP.Newline();

                var boxColor = Color.HotPink;
                var lng      = $"Config: {configNameP}".Length;

                logP.InfoL($"╔═{new string('═', lng)}═╗", boxColor);

                logP.Info("║ ", boxColor);
                logP.Info("Config: ", Color.Pink);
                logP.Info(configNameP.PadTo(lng - 10), Color.SpringGreen);
                logP.InfoL(" ║", boxColor);

                logP.InfoL($"╚═{new string('═', lng)}═╝", boxColor);

                logP.Newline();
            }

            var configName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";

            PrintConfigName(log, configName);
            return(configName);
        }
Example #2
0
        public override void write(LogBase data, bool is_sub = false)
        {
            //If sub, read the xml and get the last node and add everything as sub.
            try
            {
                //Get Xdocument and the root element.
                XDocument xdoc       = _getXDocument();
                XElement  xroot      = _getRoot(xdoc);
                XElement  input_node = (XElement)convert(data, is_sub);

                if (is_sub)
                {
                    //if sub, find the last node and add to it.
                    if (xroot.Elements().Count() == 0)
                    {
                        xroot.Add(new XElement(DEFAULTELEMENT));
                    }
                    XElement target_node = xroot.Elements()?.Last(); //By default get the last node
                    target_node.Add(input_node);
                }
                else
                {
                    xroot.Add(input_node); //if not sub, add to the root
                }
                xdoc.Save(file_name);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #3
0
        static void Main(string[] args)
        {
            string sLogChannel = "ionic-csharp-sample";

            // Log servity debug and lower to the console.
            String sConfigJson =
                "{ \"sinks\":  [ {\n" +
                "              \"channels\": [ \"" + sLogChannel + "\" ],\n" +
                "             \n" +
                "              \"filter\": { \"type\": \"Severity\",\n" +
                "                          \"level\": \"Debug\" },\n" +
                "                         \n" +
                "              \"writers\": [\n" +
                "                           { \"type\": \"Console\" }\n" +
                "                         ]\n" +
                "            } ] }";


            // Initialize logger
            LogBase logger = LogFactory.Instance.CreateFromConfig(sConfigJson);

            Log.SetSingleton(logger);

            Log.LogDebug(sLogChannel, "Sample log entry");

            WaitForInput();
        }
Example #4
0
        /// <summary>
        /// 数据库架构处理。
        /// </summary>
        /// <param name="context">上下文对象。</param>
        public DatabaseSchemaProcessResults Process(DatabaseSchemaContext context)
        {
            string fullName = TypeExtensions.FullName2(this.GetType());

            if (!_attribute.IsValid)
            {
                context.Log.Warning("{0}.Attribute.IsValid=false,[{1}]{2},{3}", fullName, _attribute.Order, _attribute.TableName, _attribute.Description);
                return(DatabaseSchemaProcessResults.Ignore);
            }
            context.DataContext.ChangeDatabase();
            context.Log.Info("执行 [{0} {1}] {2} {3} {4}",
                             EnumExtensions.ToName(_attribute.Type).PadRight(6, ' '), _attribute.Order.ToString().PadRight(8, ' '),
                             _attribute.TableName.PadRight(32, ' '), _attribute.Description.PadRight(32, ' '),
                             fullName);
            DatabaseSchemaProcessResults result;

            try {
                result = OnProcess(context);
                context.Log.Info("     [{0}] {1}", EnumExtensions.ToName(result), fullName);
            } catch (System.Exception error) {
                result = DatabaseSchemaProcessResults.Error;
                context.Log.Info("     [{0}] {1}", EnumExtensions.ToName(result), fullName);
                context.Log.Error(LogBase.ExceptionToString(error));
            }
            return(result);
        }
        /// <summary>
        /// The default constructor
        /// </summary>
        /// <param name="taskInfo">The task to run</param>
        /// <param name="backupImageLocation">The exact image location in temp directory</param>
        /// <param name="log">The opened log instance</param>
        /// <exception cref="ArgumentNullException">taskInfo or log or backupImageLocation is null or empty</exception>
        /// <exception cref="InvalidOperationException">Log is not opened</exception>
        public AfterBackupTask(BackupEventTaskInfo taskInfo, string backupImageLocation, ProcessPriorityClass priority, LogBase log)
        {
            if (taskInfo == null)
            {
                throw new ArgumentNullException("taskInfo");
            }

            if (string.IsNullOrEmpty(backupImageLocation))
            {
                throw new ArgumentNullException("backupImageLocation");
            }

            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            if (!log.IsOpened)
            {
                throw new InvalidOperationException("Log is not opened");
            }

            _taskName            = Translation.Current[610] + taskInfo.ToString() + " :";
            _taskInfo            = taskInfo;
            _backupImageLocation = backupImageLocation;
            _priority            = priority;
            _log = log;
        }
Example #6
0
 public CopyJob(StorageBase storage, string imageFileToCopy, bool enableEncryption, LogBase log)
 {
     _storage          = storage;
     _imageFileToCopy  = imageFileToCopy;
     _enableEncryption = enableEncryption;
     _log = log;
 }
Example #7
0
        /// <summary>
        /// 记录debug日志
        /// </summary>
        /// <param name="debugInfo">debug信息</param>
        /// <param name="args">请求参数</param>
        /// <param name="returnVal">返回参数</param>
        /// <param name="keyWord">自定义信息</param>
        public static void Debug(string debugInfo, object args = null, object returnVal = null, Dictionary <string, object> keyWord = null)
        {
            // 调用链+1
            LogSpan logSpan      = LogSpan.Extend(LogContext.Current);
            var     functionName = GetStackTrace();

            Task.Run(() =>
            {
                try
                {
                    LogBase log = new LogBase
                    {
                        CustomerInfo = keyWord ?? new Dictionary <string, object>(),
                        LogSpan      = logSpan,
                        LogLevel     = LogLevel.Warning,
                    };
                    log.LogSpan.FunctionName = functionName;
                    log.LogSpan.ParamIn      = args?.ToJson() ?? string.Empty;
                    log.LogSpan.ParamOut     = returnVal?.ToJson() ?? string.Empty;
                    log.CustomerInfo.Add("DebugInfo", string.IsNullOrWhiteSpace(debugInfo) ? string.Empty : debugInfo);
                    if (!LogFilter(log.LogLevel))
                    {
                        _logger.Write(log);
                    }
                }
                catch (Exception ex)
                {
                    InnerTxtLog.WriteException(ex, "记录Debug日志异常,参数:" + new { debugInfo, args, returnVal, keyWord }.ToJson());
                }
            });
        }
Example #8
0
    static LogBase()
    {
        LogBase empty = new LogBase("Empty");

        empty._levels.Add("!");
        _empty = empty;
    }
Example #9
0
        static void Main(string[] args)
        {
            string sLogChannel = "ionic-csharp-sample";
            string dateTime    = DateTime.Now.ToString("yyyy-MM-dd_HH.mm");
            string logFilePath = "sample_" + dateTime + ".log";

            // Log servity debug and lower to a file.
            String sConfigJson =
                "{ \"sinks\":  [ {\n" +
                "              \"channels\": [ \"" + sLogChannel + "\" ],\n" +
                "             \n" +
                "              \"filter\": { \"type\": \"Severity\",\n" +
                "                          \"level\": \"Debug\" },\n" +
                "                         \n" +
                "              \"writers\": [\n" +
                "                           { \"type\": \"File\",\n" +
                "                           \"filePattern\": \"" + logFilePath + "\"}\n" +
                "                         ]\n" +
                "                }\n" +
                "              ]\n" +
                "}";

            // Initialize logger
            LogBase logger = LogFactory.Instance.CreateFromConfig(sConfigJson);

            Log.SetSingleton(logger);

            Console.WriteLine("Logging to file: " + logFilePath);

            // Log to file
            Log.LogDebug(sLogChannel, "LogToFile Sample");
            Log.LogDebug(sLogChannel, "Sample log entry");

            WaitForInput();
        }
Example #10
0
        private static LogBase GetInstance(LogTarget target)
        {
            lock (Padlock)
            {
                switch (target)
                {
                case LogTarget.File:
                {
                    // logger = new FileLogger();
                }
                break;

                case LogTarget.Console:
                {
                    logger = new ConsoleLogger();
                }
                break;

                case LogTarget.EventLog:
                {
                    // logger = new EventLogger();
                }
                break;

                default:
                    return(null);
                }
            }

            return(logger);
        }
Example #11
0
 /// <summary>
 /// 注册程序集。
 /// </summary>
 /// <param name="assembly"></param>
 /// <returns></returns>
 public System.Collections.Generic.List <DatabaseSchemaHandler> RegisterAssembly(System.Reflection.Assembly assembly)
 {
     System.Collections.Generic.List <DatabaseSchemaHandler> list = new System.Collections.Generic.List <DatabaseSchemaHandler>();
     if (assembly == null ||
         assembly.FullName.StartsWith("System") ||
         assembly.FullName.StartsWith("mscorlib")
         //|| assembly.IsDynamic
         )
     {
         return(list);
     }
     _log.Info("反射程序集:{0}", assembly.FullName);
     System.Type[] types;
     try {
         types = assembly.GetExportedTypes();
     } catch (System.Exception error) {
         _log.Warning("反射程序集失败:{0}\r\n{1}", assembly.FullName, LogBase.ExceptionToString(error));
         return(list);
     }
     foreach (System.Type type in types)
     {
         DatabaseSchemaHandler item = RegisterType(type);
         if (item == null)
         {
             continue;
         }
         list.Add(item);
     }
     return(list);
 }
Example #12
0
        /// <summary>
        /// 注册类型。
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public DatabaseSchemaHandler RegisterType(System.Type type)
        {
            if (type == null || !type.IsClass || type.IsAbstract ||
                !TypeExtensions.IsInheritFrom(type, typeof(DatabaseSchemaHandler)))
            {
                return(null);
            }
            DatabaseSchemaHandler handler = null;
            string key = type.FullName;

            if (_caches.TryGetValue(key, out handler))
            {
                return(handler);
            }
            string fullName = TypeExtensions.FullName2(type);

            try {
                _log.Info("创建实例:{0}", fullName);
                handler = (DatabaseSchemaHandler)FastWrapper.CreateInstance(type);
                _caches.Add(key, handler);
                _list.Add(handler);
                ClassOrder(handler.Attribute.TableName, handler.Attribute.Order);
                CacheRef(type.Assembly, handler);
                return(handler);
            } catch (System.Exception error) {
                _log.Warning("创建实例失败:{0}\r\n{1}", fullName, LogBase.ExceptionToString(error));
                return(null);
            }
        }
Example #13
0
        static int Main(string[] args)
        {
            LogBase logger = LogFactory.GetInstance.CreateSimple("sample.log", false, LogSeverity.SEV_DEBUG);

            Log.SetSingleton(logger);

            Agent agent = new Agent();

            agent.Initialize();

            string input = "Hello World";

            // Setup a Chunk Crypto object to handle Ionic encryption
            ChunkCipherAuto chunkCrypto = new ChunkCipherAuto(agent);

            // Encrypt the string using an Ionic-managed key, and validate the response
            string encryptedText = null;

            try
            {
                chunkCrypto.Encrypt(input, ref encryptedText);
            }
            catch (SdkException e)
            {
                Console.WriteLine("Error encrypting: {0}", e.Message);
                Console.ReadKey();
                return(-2);
            }

            chunkCrypto.Encrypt(input, ref encryptedText);
            Console.WriteLine("Plain Text: {0}", input);
            Console.WriteLine("Ionic Chunk Encrypted Text: {0}", encryptedText);
            Console.ReadKey();
            return(0);
        }
Example #14
0
    /// <summary>
    /// Backup log files to [FileName].bak; this is to prevent huge log files
    /// </summary>
    /// <param name="LogFilePath">Path to the log file</param>
    /// <param name="timeSpanInDays">Days until backed up; uses file creation time</param>
    public static void BackupLogs(string LogFilePath, int timeSpanInDays = 0)
    {
        LogFile = LogFilePath;

        logger = new FileLogger();
        logger.BackupLogs(LogFile, timeSpanInDays);
    }
Example #15
0
 public static void WriteLog(UserSession session, LogBase log)
 {
     if (log == null) return;
     log.worldid = zoneid;
     log.svrip = sip;
     if (session != null)
     {
         log.key = session.key;
         log.userip = session.IP.Address;
         log.domain = (int)(session.domain);
         if (log.opopenid == null)
         {
             log.opopenid = session.UserID;
         }
         if (log.opuid == 0)
         {
             PlayerBusiness player = session.Player;
             if (player != null)
             {
                 log.opuid = player.PID;
                 log.worldid = session.zoneid;
             }
         }
     }
     m_logs.Enqueue(log);
 }
Example #16
0
        /// <summary>
        /// Called after the application has been initiated
        /// </summary>
        public static void PostStart()
        {
            LogBase Logger = Bootstrapper.Resolve <LogBase>(new NullLogger());

            Logger.LogMessage("Starting post start tasks", MessageType.Info);
            Bootstrapper.Resolve <TaskManager>().Run(RunTime.PostStart);
        }
Example #17
0
        public static void Log(LogTarget target, string message, bool isError = false)
        {
            if (_enableLogging)
            {
                switch (target)
                {
                case LogTarget.File:
                    _logger = new FileLogger();
                    _logger.Log(message, isError);
                    break;

                case LogTarget.Database:
                    _logger = new DBLogger();
                    _logger.Log(message, isError);
                    break;

                case LogTarget.EventLog:
                    _logger = new EventLogger();
                    _logger.Log(message, isError);
                    break;

                default:
                    return;
                }
            }
        }
Example #18
0
        public override void write(LogBase data, bool is_sub = false)
        {
            List <LogBase> _towriteList = new List <LogBase>();

            _towriteList.Add(data);
            write(_towriteList, is_sub);
        }
Example #19
0
        public static void Config(this LogBase log, object config, string configName)
        {
            var titleColor           = Color.GreenYellow;
            var configColor          = Color.LimeGreen;
            var configImportantColor = Color.DeepPink;

            void PrintInitTitle(string str)
            {
                log.InfoL(str, titleColor);
                log.InfoL(new string('▀', str.Length), titleColor);
            }

            PrintInitTitle(configName);
            var json  = JsonConvert.SerializeObject(config, Formatting.Indented);
            var lines = json.Split(new[] { '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var line in lines)
            {
                var c = configColor;
                if (line.ToLowerInvariant().Contains("connectionstring"))
                {
                    c = configImportantColor;
                }
                log.InfoL(line, c);
            }
            log.Newline();
        }
Example #20
0
        public override string log(Exception exception, string comments = null, string property_name = null, bool in_memory = false, bool is_sub = false)
        {
            LogBase _exceptionLog = _buildException(exception, property_name, comments);

            _log(_exceptionLog, in_memory, is_sub);
            return(_exceptionLog.Id);
        }
Example #21
0
        public override string log(string key, string value, string comments = null, string property_name = null, bool in_memory = false, bool is_sub = false)
        {
            LogBase _kvpLog = _buildKVP(key, value, property_name, comments);

            _log(_kvpLog, in_memory, is_sub);
            return(_kvpLog.Id);
        }
Example #22
0
    public BotClient(string token, string chatid)
    {
        logger   = new FileLogger(false);
        settings = new Settings();

        chat_id = chatid.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
        try
        {
            telebotClient = new TelegramBotClient(token);
        }
        catch (System.ArgumentException e)
        {
            logger.Log(string.Format("TelegramBotClient ERROR: {0}", e.Message), true);
            logger.Close();
            throw new Exception("ERROR: Telegram Bot Client not init!");
        }

        var me = telebotClient.GetMeAsync().Result;

        logger.Log(string.Format("Hello! I am user {0} and my name is {1}.", me.Id, me.FirstName), true);
        if (chatid == "")
        {
            logger.Log("Chat ID not set yet", true);
        }

        telebotClient.OnMessage += Bot_OnMessage;
        telebotClient.StartReceiving();
    }
Example #23
0
        /// <summary>
        /// Log the message
        /// </summary>
        /// <param name="message">String value of the message</param>
        /// <param name="msg_type">Type of message</param>
        /// <param name="property_name">Some associated property name</param>
        /// <param name="in_memory">If false, the data is written directly on to the file. If true, the date is stored in memory until dumped.</param>
        /// <returns>GUID value of the log messgae</returns>
        public override string log(string message, MessageType msg_type = MessageType.information, string property_name = null, bool in_memory = false, bool is_sub = false)
        {
            LogBase _infoLog = _buildInfo(message, property_name, msg_type);

            _log(_infoLog, in_memory, is_sub);
            return(_infoLog.Id);
        }
Example #24
0
        static void Main(string[] args)
        {
            logger = new FileLogger(false);
            var settings = new Settings();

            settings.Read();

            if (Settings.DefaultToken == "")
            {
                logger.Log("ERROR: Token not set!", true);
                logger.Close();
                throw new Exception("ERROR: Token not set!");
            }

            var exit = new ExitWait();

            exit.Start();

            if (Settings.DefaultStartTele == "ON")
            {
                new PipeTeleServer();
            }
            if (Settings.DefaultStartEmail == "ON")
            {
                new PipeEmailServer();
            }
        }
Example #25
0
 /// <summary>
 /// 记录info信息
 /// </summary>
 /// <param name="logSpan">日志段</param>
 /// <param name="paramOut">内容</param>
 internal static void InnerInfo(LogSpan logSpan, string paramOut = "")
 {
     Task.Run(() =>
     {
         try
         {
             LogBase log = new LogBase
             {
                 CustomerInfo = new Dictionary <string, object>(),
                 LogSpan      = logSpan,
                 LogLevel     = LogLevel.Info,
             };
             log.LogSpan.ParamOut = paramOut;
             log.CustomerInfo.Add("Content", logSpan.FunctionName ?? string.Empty);
             if (!LogFilter(log.LogLevel))
             {
                 _logger.Write(log);
             }
         }
         catch (Exception ex)
         {
             InnerTxtLog.WriteException(ex, "记录内部Info日志异常,参数:" + new { paramOut, logSpan }.ToJson());
         }
     });
 }
Example #26
0
    public void Append(LogBase newLog)
    {
        if (newLog.end < this.start)
        {
            this.dataArray.InsertRange(0, newLog.dataArray);
            this.start = newLog.start;
        }
        else if (newLog.start > this.end)
        {
            this.dataArray.AddRange(newLog.dataArray);
            this.end = newLog.end;
        }
        else
        {
            // TODO: sort this.dataArray after appending newLog.dataArray,
            // beause this.dataArray is then mixed up.
            this.dataArray.AddRange(newLog.dataArray);

            if (this.start > newLog.start)
            {
                this.start = newLog.start;
            }

            if (this.end < newLog.end)
            {
                this.end = newLog.end;
            }
        }
    }
Example #27
0
    public static LogBase CreateLogInstanceFromFile
        (string filename, LogFormat format)
    {
        LogBase logInstance = LogBase.CreateLogInstance(format);

        logInstance.ReadFile(filename);
        return(logInstance);
    }
Example #28
0
    public PipeTeleServer()
    {
        Console.OutputEncoding = System.Text.Encoding.UTF8;

        PipeName  = Settings.DefaultTPipeName;
        botClient = new BotClient(Settings.DefaultToken, Settings.DefaultChatId);
        logger    = new FileLogger(false);

        int i;

        Thread[] servers = new Thread[numThreads];

        logger.Log(string.Format("\nStart Telegram Named pipe server stream {0}\n", PipeName), true);
        logger.Log("Waiting for client connect...", true);
        logger.Log("Press 'q' to exit", true);

        for (i = 0; i < numThreads; i++)
        {
            servers[i] = new Thread(ServerThread);
            servers[i].Start();
        }
        Thread.Sleep(250);

        Task.Factory.StartNew(() =>
        {
            while (!ExitWait.exit)
            {
                for (int j = 0; j < numThreads; j++)
                {
                    if (servers[j] != null)
                    {
                        if (servers[j].Join(250))
                        {
                            logger.Log(string.Format("Telegram Server thread[{0}] finished.", servers[j].ManagedThreadId));
                            servers[j].Abort();
                            servers[j] = null;
                        }
                    }
                    else
                    {
                        servers[j] = new Thread(ServerThread);
                        servers[j].Start();
                    }
                }
            }

            for (int j = 0; j < numThreads; j++)
            {
                if (servers[j] != null)
                {
                    servers[j].Abort();
                    servers[j] = null;
                }
            }

            logger.Log(string.Format("\nTelegram Server {0} stops, exiting.", PipeName), true);
        });
    }
Example #29
0
        /// <summary>
        /// Called pre application start
        /// </summary>
        public static void PreStart()
        {
            BatComputer.PreStart();
            LogBase Logger = BatComputer.Bootstrapper.Resolve <LogBase>(new NullLogger());

            Logger.LogMessage("Current asset helpers: {0}", MessageType.Debug, BatComputer.Bootstrapper.Resolve <AssetManager>().ToString());
            Logger.LogMessage("Current serializers: {0}", MessageType.Debug, BatComputer.Bootstrapper.Resolve <SerializationManager>().ToString());
            DependencyResolver.SetResolver(new Bootstrapper.DependencyResolver(BatComputer.Bootstrapper));
        }
 private void PopulateDefaults(LogBase log)
 {
     log.ApplicationName = App;
     log.AppDomain       = AppDomain.CurrentDomain.FriendlyName;
     log.CorrelationId   = CorrelationId;
     log.StackId         = StackId;
     log.Message         = Message;
     log.TenantId        = TenantId;
 }
Example #31
0
        static int Main(string[] args)
        {
            LogBase logger = LogFactory.GetInstance.CreateSimple("sdk.log", false, LogSeverity.SEV_DEBUG);

            Log.SetSingleton(logger);

            // Set constants to use for the ISAgentDeviceProfilePersistorPassword
            string passwordSepPath     = "profiles.pw"; //NOTE: On Linux, this file should typically be placed in ~/.ionicsecurity/profiles.pw
            string passwordSepPassword = "******";

            // First create an agent that will try to read in the SEP stored with a password persistor.
            DeviceProfilePersistorPassword passwordPersistor = new DeviceProfilePersistorPassword();

            passwordPersistor.FilePath = passwordSepPath;
            passwordPersistor.Password = passwordSepPassword;

            // Try reading with this persistor, to see if we have a password persisted SEP already:
            string sActiveDeviceId = null;
            List <IonicSecurity.SDK.DeviceProfile> lstProfiles = new List <IonicSecurity.SDK.DeviceProfile>();

            try
            {
                passwordPersistor.LoadAllProfiles(ref lstProfiles, ref sActiveDeviceId);
            }
            catch (SdkException e)
            {
                Console.WriteLine("Error loading from password persistor: {0}", e.Message);
                if (e.ErrorCodeEnum == ErrorCode.AGENT_RESOURCE_NOT_FOUND)
                {
                    Console.WriteLine("The file for the password persistor was not found at {0}.", passwordSepPath);
                }
                Console.WriteLine("We will now try to convert a default persistor SEP to the password persisted SEP for you.");
                if (0 != convertSepDefaultToPassword(passwordSepPath, passwordSepPassword))
                {
                    Console.ReadKey();
                    return(-2);
                }
                Console.WriteLine("A password protected SEP should now exist.");
            }

            // Now that we have a password protected SEP, we can load it as we normally would when intitializing an agent:
            Agent agent = new Agent();

            try
            {
                agent.Initialize(passwordPersistor);
                Console.WriteLine("A password protected SEP was loaded from {0}", passwordSepPath);
                Console.WriteLine("{0} were loaded.", agent.AllProfiles.Count);
            }
            catch (SdkException e)
            {
                Console.WriteLine("Error initalizing agent: {0}", e.Message);
            }

            Console.ReadKey();
            return(0);
        }
Example #32
0
 public void WriteLog(LogBase log)
 {
     if (log.opuid == 0)
     {
         log.opuid = this.PID;
     }
     if (log.opopenid == null)
     {
         log.opopenid = this.UserID;
     }
     ServerLogger.WriteLog(this.m_session, log);
 }
Example #33
0
 /// <summary>
 /// 提交到服务器.
 /// </summary>
 /// <param name="log"></param>
 /// <returns></returns>
 public bool Request(LogBase log)
 {
     sb.Clear();
     try
     {
         string query = log.ToString(sb);
         int offset = Encoding.UTF8.GetBytes(query, 0, query.Length, sendBuffer, headLen) + headLen;
         using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
         {
             s.Connect(m_host);
             if (!s.Connected)
             {
                 try
                 {
                     m_host = CreateEndPoint(hostStr);
                 }
                 catch (Exception err)
                 {
                     LogWrapper.Error(err);
                     m_host = null;
                 }
                 return false;
             }
             Buffer.BlockCopy(sendEnds, 0, sendBuffer, offset, sendEnds.Length);
             s.Send(sendBuffer, 0, offset + sendEnds.Length, SocketFlags.None);
             int len = 0;
             while (true)
             {
                 int bytes = s.Receive(recvBuffer, len, recvBuffer.Length - len, SocketFlags.None);
                 if (bytes == 0)
                 {
                     break;
                 }
                 len += bytes;
             }
             string result = (Encoding.UTF8.GetString(recvBuffer, 0, len));
             // TODO:检查是否写入成功...
             return result.Contains("\"ret\":0");
         }
     }
     catch
     {
         return false;
     }
 }
        /// <summary>
        /// Attempts to map a dictionary using the LogMappings
        /// </summary>
        /// <param name="Input">The log to map</param>
        /// <param name="Output">A dictionary of mapped key value pairs</param>
        /// <returns></returns>
        public IEnumerable<Exception> TryMap(LogBase Input, out IDictionary<string, string> Output)
        {
            List<Exception> errors = new List<Exception>();
            if (LogMappingsRules.ContainsKey(Input.Type))
            {
                bool ErrorOccurred = false;
                var typePolicy = LogMappingsRules[Input.Type];
                if (typePolicy.Conditions != null)
                {
                    // filtering based on condition is also available, a log must have a param set to a specific value. This is used to exclude the Snapshot quality logs
                    foreach (var condition in typePolicy.Conditions)
                    {
                        if (!Input.Data.ContainsKey(condition.Key) || Input.Data[condition.Key] != condition.Value)
                        {
                            // this log did not satisfy the condition
                            errors.Add(new Exception(string.Format("Log condition '{0}' not met for log {1}.", condition.Key, Input.Type)));
                            ErrorOccurred = true;
                        }
                    }
                }

                if (!ErrorOccurred)
                {
                    Output = new Dictionary<string, string>();
                    foreach (var policy in typePolicy.Values)
                    {
                        if (Input.Data.ContainsKey(policy.OriginalKey))
                        {
                            string value = Input.Data[policy.OriginalKey];
                            if (value != null)
                            {
                                if (policy.OriginalKey == LogAttributes.Type)
                                {
                                    if (typePolicy.SerializedId != null)
                                        Output.Add(policy.NewKey, typePolicy.SerializedId);
                                }
                                else
                                {
                                    Output.Add(policy.NewKey, value);
                                }
                            }
                            else if (!policy.Optional)
                            {
                                // policy not found for the log value
                                errors.Add(new Exception(string.Format("Log property '{0}' must be set.", policy.OriginalKey)));
                                ErrorOccurred = true;
                            }
                        }
                        else
                        {
                            // policy not found for the log value
                            errors.Add(new Exception(string.Format("Log property '{0}' not found.", policy.OriginalKey)));
                            ErrorOccurred = true;
                        }
                    }
                    if (ErrorOccurred)
                        Output.Add("err", "1");
                }
                else
                    Output = null;
            }
            else
            {
                // policy not found for the log type
                Output = null;
                errors.Add(new Exception(string.Format("Mapping Rule not found for log type '{0}'", Input.Type)));
            }

            return errors;
        }
 /// <summary>
 /// Uses the rules to determine which logs to filter.
 /// </summary>
 /// <param name="Log">The log that is going to be logged.</param>
 /// <returns>True indicates the log should be logged and not filtered.</returns>
 public bool IncludeLog(LogBase Log)
 {
     return LogMappingsRules.ContainsKey(Log.Type);
 }
Example #36
0
    private void LoadSelectedLogFiles(ArrayList logFiles)
    {
        int count = 0;
        string status = "";
        this.totalLog = null;

        foreach (Hashtable logFileInfo in logFiles)
        {
            string fn = (String) logFileInfo["Filename"];
            LogFormat format = (LogFormat) logFileInfo["Format"];

            if (this.totalLog == null)
                this.totalLog = LogBase.CreateLogInstanceFromFile(fn, format);
            else
                this.totalLog.Append(LogBase.CreateLogInstanceFromFile(fn,
                            format));

            if (format != this.totalLog.Format)
                this.ShowDifferentLogFormatDialog(fn);

            status = String.Format("{0}: \"{1}\"",
                    Drohne.i18n("Loaded File"), fn);

            this.statusbar.Push(1, status);

            if (count++ == 0)
                this.saveFilename.Extension = FilenameHelper.GetExtension(fn);
        }

        status = String.Format("{0}: {1}, {2}: {3}",
                Drohne.i18n("Files Loaded"), count,
                Drohne.i18n("Log Format"), this.totalLog.Format);

        this.statusbar.Push(1, status);

        this.PopulateSlicesTreeView();
    }
Example #37
0
    private void GetSelectedSlices()
    {
        if (this.totalLog == null)
            return;

        this.resultLog = LogBase.CreateLogInstance(this.totalLog.Format);

        for (int i = 0; i < this.slicesArray.Count; i++)
        {
            TreeIter iter;
            TreePath path = new TreePath(String.Format("{0}", i));

            if (this.slicesStore.GetIter(out iter, path))
            {
                bool selected = (bool) this.slicesStore.GetValue(iter, 1);
                if (selected)
                    this.resultLog.Append((LogBase) this.slicesArray[i]);
            }
        }
    }
Example #38
0
    public void Append(LogBase newLog)
    {
        if (newLog.end < this.start)
        {
            this.dataArray.InsertRange(0, newLog.dataArray);
            this.start = newLog.start;
        }
        else if (newLog.start > this.end)
        {
            this.dataArray.AddRange(newLog.dataArray);
            this.end = newLog.end;
        }
        else
        {
            // TODO: sort this.dataArray after appending newLog.dataArray,
            // beause this.dataArray is then mixed up.
            this.dataArray.AddRange(newLog.dataArray);

            if (this.start > newLog.start)
                this.start = newLog.start;

            if (this.end < newLog.end)
                this.end = newLog.end;
        }
    }
 public bool IncludeLog(LogBase Log)
 {
     return !(Log is TraceLog || Log is VideoQualitySnapshotLog);
 }
Example #40
0
 /// <summary>
 /// 重新写日志
 /// </summary>
 /// <param name="log"></param>
 /// <param name="retry">重试指定次数,直到写入成功</param>
 /// <param name="sleep"></param>
 private static void TryWrite(LogBase log, int retry, int sleep)
 {
     // 最多缓存4万条,大概1个小时的数据量
     const int maxCount = 40000;
     for (int i = 0; i < retry; i++)
     {
         if (m_logs.Count > maxCount)
         {
             break;
         }
         try
         {
             LogAccess.Instance.Insert(log);
             return;
         }
         catch { }
         System.Threading.Thread.Sleep(sleep);
     }
     //尝试指定次数失败或缓存过多时,写入本地日志文件
     try
     {
         sb.Clear();
         sb.Append("Logid=");
         sb.Append(log.ID.ToString());
         sb.Append("&");
         logger.Info(log.ToString(sb));
     }
     catch { }
 }