Logs are a required feature when developing server programs. Because the server needs to frequently write data into logs, a simple log function is used at the beginning.
Is to directly write log characters into the file. Close the connection. It has always been well applied. However, during stress testing, the data of each connection must be written into the log. After a period of operation, frequent disconnection and high CPU usage occur, after optimization, we can think of a lot of things that have a certain effect. After careful observation, we find that the hard disk lights are not flashing, which means that the hard disk I/0 operation is too tight. However, during the test, the hard disk is basically not read or written, and it suddenly finds that the log function affects the performance of the entire system. When writing log data, you need to open the file, write the file, and close the file. Ha, these are relatively expensive I/0 operations. The optimization method is simple. It caches data and regularly writes data to disks in batches. Based on this design idea, a new log class is developed. Exchange Space for time.
The dual-buffer algorithm is used internally. When writing information, the data is directly written to the memory, and then the thread writes the data in the memory to the disk file according to a certain interval, there are two buffer memory queues in it, using the producer = Consumer mode. writelog is the producer that writes log data and is a tfilestream object, writing data in the memory to the disk is a consumer role. The dual-buffer mode reduces interference between production and consumption. improves performance and reduces log writing time. It can barely be regarded as the actual application of a dual-Buffer Queue.
This log class is implemented based on threads. For ease of use. The internal locking mechanism is adopted. Is a thread-safe class. When the data volume is large or to facilitate Log File Management
We will generate different log file names based on certain rules. The most common is to name the log file by date. For example, 20110702.log, 20110701.log, etc.
You can change the log file name at any time.
Property filename: String read getlogfilename write setlogfilename; to modify the log file name, assign a value directly. It is also thread-safe.
Finally, we need to explain that the design idea of this log class can also be used in other aspects. Buffer, space change time is a common method in software design.
// Implementation code
Unit usflog;
Interface
Uses
Windows, messages, sysutils, variants, classes;
Type
Tsflog = Class (tthread)
Private
FLF: string; // #13 #10;
FS: tfilestream;
Fcurfilename: string;
Ffilename: string;
Fbegcount: DWORD;
Fbuffa, fbuffb: tmemorystream;
FCS: trtlcriticalsection;
Fcs_filename: trtlcriticalsection;
Flogbuff: tmemorystream;
Procedure writetofile ();
Function getlogfilename: string;
Procedure setlogfilename (const value: string );
Protected
Procedure execute (); override;
Public
Constructor create (logfilename: string );
Destructor destroy (); override;
Procedure writelog (const inbuff: pointer; insize: integer); overload;
Procedure writelog (const MSG: string); overload;
Public
Property filename: String read getlogfilename write setlogfilename;
End;
Implementation
{Tsflog}
Constructor tsflog. Create (logfilename: string );
Begin
If trim (logfilename) = ''then
Raise exception. Create ('Log filename not ""');
Inherited create (true );
//\\
Initializecriticalsection (FCS); // Initialization
Initializecriticalsection (fcs_filename); // Log File Name
// The queue Buffer A and B are used repeatedly when they are running.
Self. fbuffa: = tmemorystream. Create ();
Self. fbuffa. Size: = 1024*1024; // The initial value can be adjusted as needed
Self. fbuffb: = tmemorystream. Create ();
Self. fbuffb. Size: = 1024*1024; // The initial value can be adjusted as needed
Self. flogbuff: = self. fbuffa;
If fileexists (logfilename) then
Begin
FS: = tfilestream. Create (logfilename, fmopenwrite or fmsharedenywrite );
FS. Position: = FS. size; // if the file already exists, append the data.
End
Else
FS: = tfilestream. Create (logfilename, fmcreate or fmsharedenywrite );
Fcurfilename: = logfilename;
Ffilename: = logfilename;
FLF: = #13 #10;
// Start execution
Self. Resume ();
//\\
End;
Destructor tsflog. Destroy;
Begin
Fbuffa. Free ();
Fbuffb. Free ();
FS. Free ();
Inherited;
End;
Procedure tsflog. Execute ();
Begin
Fbegcount: = gettickcount ();
While (not self. Terminated) Do
Begin
// 2000 ms can be adjusted according to your own needs, the interval between data writing to the disk
If (gettickcount ()-fbegcount)> = 2000 then
Begin
Writetofile ();
Fbegcount: = gettickcount ();
End
Else
Sleep (200 );
End;
Writetofile ();
End;
Function tsflog. getlogfilename: string;
Begin
Entercriticalsection (fcs_filename );
Try
Result: = fcurfilename;
Finally
Leavecriticalsection (fcs_filename );
End;
End;
Procedure tsflog. setlogfilename (const value: string );
Begin
Entercriticalsection (fcs_filename );
Try
Ffilename: = value;
Finally
Leavecriticalsection (fcs_filename );
End;
End;
Procedure tsflog. writelog (const MSG: string );
Begin
Writelog (pointer (MSG), length (MSG ));
End;
Procedure tsflog. writelog (const inbuff: pointer; insize: integer );
VaR
Tmpstr: string;
Begin
Tmpstr: = formatdatetime ('yyyy-MM-DD hh: mm: SS zzz', now ());
Entercriticalsection (FCS );
Try
Flogbuff. Write (tmpstr [1], length (tmpstr ));
Flogbuff. Write (inbuff ^, insize );
Flogbuff. Write (FLF [1], 2 );
Finally
Leavecriticalsection (FCS );
End;
End;
Procedure tsflog. writetofile;
VaR
MS: tmemorystream;
Islogfilenamechanged: Boolean;
Begin
Entercriticalsection (FCS );
// Swap Buffer
Try
MS: = nil;
If flogbuff. Position> 0 then
Begin
MS: = flogbuff;
If flogbuff = fbuffa then flogbuff: = fbuffb
Else
Flogbuff: = fbuffa;
Flogbuff. Position: = 0;
End;
Finally
Leavecriticalsection (FCS );
End;
//\\
If MS = nil then
Exit;
// Write a file
Try
FS. Write (Ms. Memory ^, ms. position );
Finally
Ms. Position: = 0;
End;
// Check whether the file name is changed
Entercriticalsection (fcs_filename );
Try
Islogfilenamechanged: = (fcurfilename <> ffilename );
Finally
Leavecriticalsection (fcs_filename );
End;
// The log file name has been modified.
If islogfilenamechanged then
Begin
Fcurfilename: = ffilename;
FS. Free ();
If fileexists (ffilename) then
Begin
FS: = tfilestream. Create (ffilename, fmopenwrite or fmsharedenywrite );
FS. Position: = FS. size;
End
Else
FS: = tfilestream. Create (ffilename, fmcreate or fmsharedenywrite );
End;
End;
End.
// Test code for log Functions
// Mainly test three functions
1) is the log writing speed fast enough?
2) Can the log class run stably with multiple threads?
3) change the name of the output log file during running
To generate a large amount of data and multi-thread stability, 120 threads are generated in the test and log functions are written at the same time.
At the same time, a timer is used to regularly modify the output log file name. The information written into the log is a random guid string.
Unit umain;
Interface
Uses
Windows, messages, sysutils, variants, classes, graphics, controls, forms,
Dialogs, usflog, stdctrls, extctrls, ActiveX;
Type
Tfrmmain = Class (tform)
Button1: tbutton;
Edit1: tedit;
Timer1: ttimer;
Procedure formcreate (Sender: tobject );
Procedure button1click (Sender: tobject );
Procedure formclose (Sender: tobject; var action: tcloseaction );
Procedure timer1timer (Sender: tobject );
Private
{Private Declarations}
Flist: tlist;
Logobj: tsflog;
Public
{Public declarations}
End;
Tsflogtest = Class (tthread)
Protected
Procedure execute (); override;
End;
VaR
Frmmain: tfrmmain;
Implementation
{$ R *. DFM}
Function getguid (): string;
VaR
ID: tguid;
Begin
Cocreateguid (ID );
Result: = guidtostring (ID );
End;
Procedure tfrmmain. formcreate (Sender: tobject );
Begin
Logobj: = tsflog. Create ('C: \ temp \ 0001. txt ');
Flist: = tlist. Create ();
End;
// Start the test
Procedure tfrmmain. button1click (Sender: tobject );
VaR
OBJ: tsflogtest;
Index: integer;
Begin
For index: = 1 to 120 do
Begin
OBJ: = tsflogtest. Create (false );
Flist. Add (OBJ );
End;
Self. timer1.enabled: = true;
End;
{Tsflogtest}
Procedure tsflogtest. Execute;
VaR
MSG: string;
Begin
While (not self. Terminated) Do
Begin
MSG: = inttostr (self. threadid) + #09 +
Getguid () +
Getguid () + getguid ();
Frmmain. logobj. writelog (MSG );
Sleep (10 );
End;
End;
Procedure tfrmmain. formclose (Sender: tobject; var action: tcloseaction );
VaR
Index: integer;
OBJ: tsflogtest;
Begin
For index: = 0 to flist. Count-1 do
Begin
OBJ: = tsflogtest (flist. items [Index]);
OBJ. Terminate ();
End;
Sleep (100 );
End;
Procedure tfrmmain. timer1timer (Sender: tobject );
VaR
Afilename: string;
Begin
Afilename: = 'C: \ temp \ '+ formatdatetime ('yyyymmd_hhmmss_zzz', now () +'. txt ';
Logobj. filename: = afilename;
End;
End.