Work Time Manager [open-source project]-create your own log component 2.0 reconstruction, manager open-source project

Source: Internet
Author: User

Work Time Manager [open-source project]-create your own log component 2.0 reconstruction, manager open-source project

 

Hello all, I'm back.

 

This time we are really starting to talk about the development ideas of small and useful modules or components in open-source projects.

 

At the same time, the software has been updated to version 1.60, supporting new user registration, you can no longer use a unified test account.

 

You can download from the following path:

1. on GitHub, download the fellow project to your local computer and generate it to obtain the latest program version.

2. If the local version is beta v0.5, you can click Update in the upper-right corner of the program.

3. For non-Microsoft developers, decompress the following package and use it.

Click to download]

 

 

 

If you do not know what software it is, read this blog:

[WPF MaterialDesign example open-source project] Work Time Manager

 

Today, let's talk about the log components of the client.

 

I do not know whether component integration is appropriate. components are components that are part of the software and can be reused.

This log class is a typical component and has many characteristics;

1. It will be used anywhere in the software

2. Always called

3. high usage

4. Frequent io operations

 

 

I used Log4net when I first came into contact with c #. However, at that time, I came up with the idea that a program may only be several Mb in size, A log component is better than the previous master program, which is obviously inappropriate.

So I did not graduate two years ago and started my first log component.

[. Net] Create your own log component-release version

The basic idea is still good, including thread, blocking, and resource competition.

As the saying goes, I am not afraid of tigers, and I am just doing this myself.

Write the first version of the log component that uses the thread.

 

 

However, after all, the problem is still obvious when we are young. It won't work if you hit 100 entries in a second.

So when I started c # development again, I took some time and made a refactoring.

 

First, start with the overall architecture:-old component features: * use multi-thread queues and use mutex variables to control the writing of text by the thread.
* By locking a single instance, the competition for resources is controlled. * The thread is randomly selected and the log write time sequence may be incorrect. * one thread performs a text operation at a time, the switch is operated in one thread, and only one variable is written at a time.-advantage: * multi-threaded operation, improving operation efficiency on the surface * locking a single instance to ensure only-disadvantage: * performance bottom, excessive io operations lead to severe performance redundancy * write only one at a time-improvement * use producer consumer mode, separate operations, limit the number of threads * use stack queue, first-in-first-out, ensure the log Order * single-instance IO variables, and perform batch write operation transformation results:
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Threading;

namespace Helper
{
    public static class LogHelper
    {
        private static readonly Queue LogQueue = new Queue ();

        private static bool _isStreamClose = true;

        private static bool _isThreadBegin = false;

        private static StreamWriter _fileStreamWriter;

        private static readonly string fileName = @ "BugLog.txt";

        static int _intervalTime = 10000; // 10s

        static System.Timers.Timer _timer = new System.Timers.Timer (_intervalTime);

        /// <summary>
        /// Add log queue
        /// </ summary>
        /// <param name = "message"> </ param>
        public static void AddLog (string message)
        {
            string logContent = $ "[{DateTime.Now:yyyy-MM-dd hh: mm: ss}] => {message}";
            LogQueue.Enqueue (logContent);
            if (! _isThreadBegin)
            {
                BeginThread ();
            }
        }

        public static void AddLog (Exception ex)
        {
            var logContent = $ "[{DateTime.Now:yyyy-MM-dd hh: mm: ss}] error occurred at: {ex.Source}, \ r \ n content: {ex.Message}";
            logContent + = $ "\ r \ n Trace: {ex.StackTrace}";
            LogQueue.Enqueue (logContent);
            if (! _isThreadBegin)
            {
                BeginThread ();
            }
        }

        /// <summary>
        /// Read a piece of data from the log queue
        /// </ summary>
        /// <returns> </ returns>
        private static object GetLog ()
        {
            return LogQueue.Dequeue ();
        }

        /// <summary>
        /// Start the timing query thread
        /// </ summary>
        public static void BeginThread ()
        {
            _isThreadBegin = true;

            // Instantiate the Timer class and set the interval time to 10000 ms;

            _timer.Interval = _intervalTime;

            _timer.Elapsed + = SetLog;

            // The event is executed when the time is reached;

            _timer.AutoReset = true;

            // Set whether to execute once (false) or keep executing (true);

            _timer.Enabled = true;
        }


        /// <summary>
        /// Write to log
        /// </ summary>
        private static void SetLog (object source, System.Timers.ElapsedEventArgs e)
        {
            if (LogQueue.Count == 0)
            {
                if (_isStreamClose) return;
                _fileStreamWriter.Flush ();
                _fileStreamWriter.Close ();
                _isStreamClose = true;
                return;
            }
            if (_isStreamClose)
            {
                Isexist ();
                string errLogFilePath = Environment.CurrentDirectory + @ "\ Log \" + fileName.Trim ();
                if (! File.Exists (errLogFilePath))
                {
                    FileStream fs1 = new FileStream (errLogFilePath, FileMode.Create, FileAccess.Write);
                    _fileStreamWriter = new StreamWriter (fs1);
                }
                else
                {
                    _fileStreamWriter = new StreamWriter (errLogFilePath, true);
                }
                _isStreamClose = false;
            }

            var strLog = new StringBuilder ();

            var onceTime = 50;

            var lineNum = LogQueue.Count> onceTime? onceTime: LogQueue.Count;

            for (var i = 0; i <lineNum; i ++)
            {
                strLog.AppendLine (GetLog (). ToString ());
            }

            _fileStreamWriter.WriteLine (strLog.ToString ());

        }

        /// <summary>
        /// Determine whether there is a log file
        /// </ summary>
        private static void Isexist ()
        {
            string path = Environment.CurrentDirectory + @ "\ Log \";
            if (! File.Exists (path))
            {
                Directory.CreateDirectory (path);
            }
        }
    }
} 

 

The Code does not have any third-party component application. You can directly copy this file to use it.

Currently, this is only a basic demo,

Of course, if you want to know how to improve it in the future, you can follow GitHub of this project.

 

Of course, we look forward to your better suggestions. Let's learn together. You have good ideas and don't want to write them. I will help you implement them!

 

Everyone is welcome. Only criticism is the best motivation for moving forward!

 

At the same time, the online API of WorkTimeManager will be available soon. You are welcome to develop the corresponding peripheral applications!

Please note: http://api.timemanager.online/

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.