//        public void Start() {
//            LogStreamWriter.Write(ExperimentInfo);
//            _StartTime = DateTime.Now;
//            Action wrappedAction = () =>
//            {
//                ExecThread = Thread.CurrentThread;
//                StartWithoutTimeout();
//            };
//            IAsyncResult result = wrappedAction.BeginInvoke(null, null);
//
//            if (result.AsyncWaitHandle.WaitOne(_Timeout)) {
//                wrappedAction.EndInvoke(result);
//            }
//            else
//            {
//                if (!ExecThread.IsAlive) return;
//                ExecThread.Abort();
//                LogStreamWriter.Write(TimeoutKill);
//                _Now = State.Error;
//                return;
//            }
//            LogStreamWriter.Write(ExperimentTimeInfo);
//            SolutionStreamWriter.Write(SolutionInfo);
//            LogStreamWriter.Write(ResultInfo);
//        }

        public async void Start()
        {
            _StartTime = DateTime.Now;
            _Now       = State.Running;
            LogStreamWriter.Write(ExperimentInfo);
            Task _Task;

            _Task = Task.Run(StartWithoutTimeout);
            var timeoutCancellationTokenSource = new CancellationTokenSource();

            if (await Task.WhenAny(_Task, Task.Delay(_Timeout, timeoutCancellationTokenSource.Token)) == _Task)
            {
                // task completed within timeout
                timeoutCancellationTokenSource.Cancel();
                _Now = State.Finished;
                LogStreamWriter.Write(ExperimentTimeInfo);
                SolutionStreamWriter.Write(SolutionInfo);
                LogStreamWriter.Write(ResultInfo);
                await _Task;
            }
            else
            {
                // timeout logic
                LogStreamWriter.Write(TimeoutKill);
                _Now = State.Error;
            }
        }
        private void LogRotateNowLocked()
        {
            //if (externalLog == true)
            //    delegateClearLogText();
            //else
            //    ;

            try
            {
                m_sw.Close();

                //logIndex = (logIndex + 1) % logRotateFiles;
                //m_fileName = LogFileName();

                LogToArchive();

                m_sw = new LogStreamWriter(m_fileName, false, Encoding.GetEncoding("windows-1251"));
                m_fi = new FileInfo(m_fileName);
            }
            catch (Exception e)
            {
                /*m_sw.Close ();*/
                m_sw = null;
                m_fi = null;
            }
        }
        /// <summary>
        /// Конструктор
        /// </summary>
        /// <param name="name">имя лог-файла</param>
        /// <param name="extLog">признак - внешнее логгирование</param>
        /// <param name="updateLogText">функция записи во внешний лог-файл</param>
        /// <param name="clearLogText">функция очистки внешнего лог-файла</param>
        //private Logging(string name, bool extLog, DelegateStringFunc updateLogText, DelegateFunc clearLogText)
        private Logging(string name)
        {
            //externalLog = extLog;
            logRotateSize   = logRotateSizeDefault;
            logRotateFiles  = logRotateFilesDefault;
            m_fileNameStart = m_fileName = name;
            sema            = new Semaphore(1, 1);

            try {
                m_sw = new LogStreamWriter(m_fileName, true, Encoding.GetEncoding("windows-1251"));
                m_fi = new FileInfo(m_fileName);
            }
            catch (Exception e) {
                //Нельзя сообщить программе...
                //throw new Exception(@"private Logging::Logging () - ...", e);
                ProgramBase.Abort();
            }

            logRotateCheckLast      = DateTime.Now;
            logRotateChekMaxSeconds = 60;

            //logIndex = 0;
            //delegateUpdateLogText = updateLogText;
            //delegateClearLogText = clearLogText;

            start();
        }
Exemple #4
0
        private void LogWindow_Load(object sender, EventArgs e)
        {
            sw = Console.Out;
            LogStreamWriter lsw = new LogStreamWriter(richTextBoxOutput);

            Console.SetOut(lsw);
        }
Exemple #5
0
 public void WriteLine(string line)
 {
     using (StreamWriter writer = new LogStreamWriter(logFile, true))
     {
         writer.WriteLine(DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss]") + " Thread ID: " + Thread.CurrentThread.ManagedThreadId);
         writer.WriteLine(line);
     }
 }
 public void Abort()
 {
     if (ExecThread != null && ExecThread.IsAlive)
     {
         ExecThread.Abort();
         LogStreamWriter.Write(ManuallyKill);
     }
     _Now = State.Init;
 }
 public bool SetTimeout(int time)
 {
     if (time <= 0 || time > 86400)
     {
         LogStreamWriter.Write(TimeoutLogicalError);
         return(false);
     }
     _Timeout = time * 1000;
     return(true);
 }
Exemple #8
0
        public override void Log(string logText, LogSeverity severity)
        {
            if (!_initialized)
            {
                throw new TypeInitializationException("Log provider not initialized", new Exception("UpdateBaseStream wasn't called"));
            }

            lock (StreamLockObject)
            {
                logText = FormatProvider.Format($"[{severity}] {logText}");
                LogStreamWriter.WriteLine(logText);
            }
        }
Exemple #9
0
 public LogUtil(string logFile, bool append)
 {
     logFile = logFile.Replace("\\", "/");
     if (logFile.Contains('/') && logFile[0] != '/')
     {
         string dir = logFile.Substring(0, logFile.LastIndexOf("/"));
         if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
     }
     this.logFile = logFile;
     using (StreamWriter writer = new LogStreamWriter(logFile, append))
     {
         writer.WriteLine("");
         writer.WriteLine("--------------------------------------------------------------------------");
         writer.WriteLine("|                 FrameDAL - Powered by Vincent Lau.                     |");
         writer.WriteLine("--------------------------------------------------------------------------");
     }
 }
Exemple #10
0
        /// <summary>
        /// Восстановление гоггирования
        /// </summary>
        public void Resume()
        {
            switch (s_mode)
            {
            case LOG_MODE.FILE:
                m_sw = new LogStreamWriter(m_fi.FullName, true, Encoding.GetEncoding("windows-1251"));

                Debug("Возобновление ведения журнала...", false);

                LogUnlock();
                break;

            case LOG_MODE.DB:
                Debug("Возобновление ведения журнала...", false);
                break;

            case LOG_MODE.UNKNOWN:
            default:
                break;
            }
        }
        /// <summary>
        /// Восстановление гоггирования
        /// </summary>
        public void Resume()
        {
            switch (s_mode)
            {
            case LOG_MODE.FILE_EXE:
            case LOG_MODE.FILE_DESKTOP:
            case LOG_MODE.FILE_LOCALDEV:
            case LOG_MODE.FILE_NETDEV:
                m_sw = new LogStreamWriter(m_fi.FullName, true, Encoding.GetEncoding("windows-1251"));

                Debug("Возобновление ведения журнала...", Logging.INDEX_MESSAGE.NOT_SET, false);

                LogUnlock();
                break;

            case LOG_MODE.DB:
                Debug("Возобновление ведения журнала...", Logging.INDEX_MESSAGE.NOT_SET, false);
                break;

            case LOG_MODE.UNKNOWN:
            default:
                break;
            }
        }
        private void threadPost(object par)
        {
            while (true)
            {
                INDEX_SEMATHREAD indx_semathread = (INDEX_SEMATHREAD)WaitHandle.WaitAny(m_arEvtThread);

                //Отправление сообщений...
                int    err    = -1;
                string toPost = string.Empty;

                if (m_listQueueMessage.Count > 0)
                {
                    switch (s_mode)
                    {
                    case LOG_MODE.DB:
                        if (m_evtConnSett.WaitOne(0, true) == true)
                        {
                            lock (m_objQueueMessage)
                            {
                                ////Отладка!!!
                                //Console.WriteLine(@"Логгирование: сообщений на вХоде=" + m_listQueueMessage.Count);

                                int indx_queue = 0
                                , cnt_running  = 0;
                                while ((indx_queue < m_listQueueMessage.Count) && (cnt_running < MAX_COUNT_MESSAGE_ONETIME))
                                {
                                    if (m_listQueueMessage[indx_queue].m_state == STATE_MESSAGE.QUEUE)
                                    {
                                        toPost += getInsertQuery(m_listQueueMessage[indx_queue]) + @";";
                                        m_listQueueMessage[indx_queue].m_state = STATE_MESSAGE.RUNNING;

                                        cnt_running++;
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    indx_queue++;
                                }
                            }

                            DbTSQLInterface.ExecNonQuery(ref s_dbConn, toPost, null, null, out err);

                            if (!(err == 0))
                            {     //Ошибка при записи сообщений...
                                retryQueueMessage();

                                disconnect();
                                m_evtConnSett.Reset();
                            }
                            else
                            {     //Успех при записи сообщений...
                                clearQueueMessage();
                            }

                            ////Отладка!!!
                            //lock (m_objQueueMessage)
                            //{
                            //    Console.WriteLine(@"Логгирование: сообщений на вЫходе=" + m_listQueueMessage.Count);
                            //    foreach (MESSAGE msg in m_listQueueMessage)
                            //        Console.WriteLine(@"Тип сообщения=" + msg.m_state.ToString ());
                            //}
                        }
                        else
                        {
                            ;     //Нет соединения с БД
                        }
                        break;

                    case LOG_MODE.FILE_EXE:
                    case LOG_MODE.FILE_DESKTOP:
                    case LOG_MODE.FILE_LOCALDEV:
                    case LOG_MODE.FILE_NETDEV:
                        bool locking = false;
                        if ((!(m_listQueueMessage == null)) && (m_listQueueMessage.Count > 0))
                        {
                            lock (m_objQueueMessage)
                            {
                                int indx_queue = 0;
                                while (indx_queue < m_listQueueMessage.Count)
                                {
                                    if (m_listQueueMessage[indx_queue].m_bSeparator == true)
                                    {
                                        toPost += MessageSeparator + Environment.NewLine;
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    if (m_listQueueMessage[indx_queue].m_bDatetimeStamp == true)
                                    {
                                        toPost += m_listQueueMessage[indx_queue].m_strDatetimeReg + Environment.NewLine;
                                        toPost += DatetimeStampSeparator + Environment.NewLine;
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    toPost += m_listQueueMessage[indx_queue].m_text + Environment.NewLine;

                                    if (m_listQueueMessage.Count == 1)
                                    {
                                        locking = m_listQueueMessage[indx_queue].m_bLockFile;
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    if (locking == false)
                                    {
                                        if ((DateTime.Now - logRotateCheckLast).TotalSeconds > logRotateChekMaxSeconds)
                                        {
                                            //Принудить к проверке размера файла
                                            locking = true;
                                        }
                                        else
                                        {
                                            ;
                                        }
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    m_listQueueMessage[indx_queue].m_state = STATE_MESSAGE.RUNNING;

                                    indx_queue++;
                                }
                            }

                            if (locking == true)
                            {
                                LogLock();
                                LogCheckRotate();
                            }
                            else
                            {
                                ;
                            }

                            if (File.Exists(m_fileName) == true)
                            {
                                try
                                {
                                    if ((m_sw == null) || (m_fi == null))
                                    {
                                        //Вариант №1
                                        //FileInfo f = new FileInfo(m_fileName);
                                        //FileStream fs = f.Open(FileMode.Append, FileAccess.Write, FileShare.Write);
                                        //m_sw = new LogStreamWriter(fs, Encoding.GetEncoding("windows-1251"));
                                        //Вариант №2
                                        m_sw = new LogStreamWriter(m_fileName, true, Encoding.GetEncoding("windows-1251"));

                                        m_fi = new FileInfo(m_fileName);
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    m_sw.Write(toPost);
                                    m_sw.Flush();
                                }
                                catch (Exception e)
                                {
                                    retryQueueMessage();

                                    /*m_sw.Close ();*/
                                    m_sw = null;
                                    m_fi = null;
                                }
                            }
                            else
                            {
                                retryQueueMessage();
                            }

                            //if (externalLog == true)
                            //{
                            //    if (timeStamp == true)
                            //        delegateUpdateLogText(DateTime.Now.ToString() + ": " + message + Environment.NewLine);
                            //    else
                            //        delegateUpdateLogText(message + Environment.NewLine);
                            //}
                            //else
                            //    ;

                            clearQueueMessage();

                            if (locking == true)
                            {
                                LogUnlock();
                            }
                            else
                            {
                                ;
                            }
                        }
                        else
                        {
                        }
                        break;

                    case LOG_MODE.UNKNOWN:
                    default:
                        break;
                    }
                }
                else
                {
                    ;
                }

                if (indx_semathread == INDEX_SEMATHREAD.STOP)
                {
                    break;
                }
                else
                {
                    m_arEvtThread[(int)INDEX_SEMATHREAD.MSG].Reset();
                }
            }
        }
Exemple #13
0
        private void threadPost(object par)
        {
            while (true)
            {
                INDEX_SEMATHREAD indx_semathread = (INDEX_SEMATHREAD)WaitHandle.WaitAny(m_arEvtThread);

                //Отправление сообщений...
                int    err    = -1;
                string toPost = string.Empty;

                if (m_listQueueMessage.Count > 0)
                {
                    switch (s_mode)
                    {
                    case LOG_MODE.DB:
                        if (m_evtConnSett.WaitOne(0) == true)
                        {
                            lock (m_objQueueMessage)
                            {
                                ////Отладка!!!
                                //Console.WriteLine(@"Логгирование: сообщений на вХоде=" + m_listQueueMessage.Count);

                                int indx_queue = 0
                                , cnt_running  = 0;
                                while ((indx_queue < m_listQueueMessage.Count) && (cnt_running < MAX_COUNT_MESSAGE_ONETIME))
                                {
                                    if (m_listQueueMessage[indx_queue].m_state == STATE_MESSAGE.QUEUE)
                                    {
                                        toPost += getInsertQuery(m_listQueueMessage[indx_queue]) + @";";
                                        m_listQueueMessage[indx_queue].m_state = STATE_MESSAGE.RUNNING;

                                        cnt_running++;
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    indx_queue++;
                                }
                            }

                            DbTSQLInterface.ExecNonQuery(ref s_dbConn, toPost, null, null, out err);

                            if (!(err == 0))
                            {     //Ошибка при записи сообщений...
                                lock (m_objQueueMessage)
                                {
                                    //Постановка ПОВТОРно сообщений в очередь
                                    foreach (MESSAGE msg in m_listQueueMessage)
                                    {
                                        if (msg.m_state == STATE_MESSAGE.RUNNING)
                                        {
                                            msg.m_state = STATE_MESSAGE.QUEUE;
                                        }
                                        else
                                        {
                                            ;
                                        }
                                    }
                                }

                                disconnect();
                                m_evtConnSett.Reset();
                            }
                            else
                            {     //Успех при записи сообщений...
                                lock (m_objQueueMessage)
                                {
                                    //Найти обработанные сообщения
                                    List <int> listIndxMsgRunning = new List <int>();
                                    foreach (MESSAGE msg in m_listQueueMessage)
                                    {
                                        if (msg.m_state == STATE_MESSAGE.RUNNING)
                                        {
                                            listIndxMsgRunning.Add(m_listQueueMessage.IndexOf(msg));
                                        }
                                        else
                                        {
                                            ;
                                        }
                                    }

                                    //Сортировать список индексов в ОБРАТном порядке
                                    // для удаления сообщений из списка по ИНДЕКСу
                                    listIndxMsgRunning.Sort(delegate(int i1, int i2) { return(i1 > i2 ? -1 : 1); });

                                    //Удалить обработанные сообщения
                                    foreach (int indx in listIndxMsgRunning)
                                    {
                                        m_listQueueMessage.RemoveAt(indx);
                                    }
                                }
                            }

                            ////Отладка!!!
                            //lock (m_objQueueMessage)
                            //{
                            //    Console.WriteLine(@"Логгирование: сообщений на вЫходе=" + m_listQueueMessage.Count);
                            //    foreach (MESSAGE msg in m_listQueueMessage)
                            //        Console.WriteLine(@"Тип сообщения=" + msg.m_state.ToString ());
                            //}
                        }
                        else
                        {
                            ;     //Нет соединения с БД
                        }
                        break;

                    case LOG_MODE.FILE:
                        bool locking = false;
                        if ((!(m_listQueueMessage == null)) && (m_listQueueMessage.Count > 0))
                        {
                            lock (m_objQueueMessage)
                            {
                                while (m_listQueueMessage.Count > 0)
                                {
                                    if (m_listQueueMessage[0].m_bSeparator == true)
                                    {
                                        toPost += MessageSeparator + Environment.NewLine;
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    if (m_listQueueMessage[0].m_bDatetimeStamp == true)
                                    {
                                        toPost += m_listQueueMessage[0].m_strDatetimeReg + Environment.NewLine;
                                        toPost += DatetimeStampSeparator + Environment.NewLine;
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    toPost += m_listQueueMessage[0].m_text + Environment.NewLine;

                                    if (m_listQueueMessage.Count == 1)
                                    {
                                        locking = m_listQueueMessage[0].m_bLockFile;
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    m_listQueueMessage[0].m_state = STATE_MESSAGE.RUNNING;
                                }
                            }

                            if (locking == true)
                            {
                                LogLock();
                                LogCheckRotate();
                            }
                            else
                            {
                                ;
                            }

                            if (File.Exists(m_fileName) == true)
                            {
                                try
                                {
                                    if ((m_sw == null) || (m_fi == null))
                                    {
                                        //Вариант №1
                                        //FileInfo f = new FileInfo(m_fileName);
                                        //FileStream fs = f.Open(FileMode.Append, FileAccess.Write, FileShare.Write);
                                        //m_sw = new LogStreamWriter(fs, Encoding.GetEncoding("windows-1251"));
                                        //Вариант №2
                                        m_sw = new LogStreamWriter(m_fileName, true, Encoding.GetEncoding("windows-1251"));

                                        m_fi = new FileInfo(m_fileName);
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    m_sw.Write(toPost);
                                    m_sw.Flush();
                                }
                                catch (Exception e)
                                {
                                    /*m_sw.Close ();*/
                                    m_sw = null;
                                    m_fi = null;
                                }
                            }
                            else
                            {
                                ;
                            }

                            //if (externalLog == true)
                            //{
                            //    if (timeStamp == true)
                            //        delegateUpdateLogText(DateTime.Now.ToString() + ": " + message + Environment.NewLine);
                            //    else
                            //        delegateUpdateLogText(message + Environment.NewLine);
                            //}
                            //else
                            //    ;

                            lock (m_objQueueMessage) {
                                m_listQueueMessage.RemoveAt(0);
                            }

                            if (locking == true)
                            {
                                LogUnlock();
                            }
                            else
                            {
                                ;
                            }
                        }
                        else
                        {
                        }
                        break;

                    case LOG_MODE.UNKNOWN:
                    default:
                        break;
                    }
                }
                else
                {
                    ;
                }

                if (indx_semathread == INDEX_SEMATHREAD.STOP)
                {
                    break;
                }
                else
                {
                    m_arEvtThread[(int)INDEX_SEMATHREAD.MSG].Reset();
                }
            }
        }