Maintain server logs

Maintain logs in a very important thing. There are a lot of ways to do this. Here I'm not going to do hard things. This is just a simple example of maintaining server logs using a shell script.

Here I'm planning to do some tasks.
  1. Delete old log files
  2. Save last log file 
  3. Zip it and save it in another place.
This can be used in your local server to maintain logs and it will be very easy because you need not delete logs every time and save logs.

Sometimes it will be not easy to understand if you are a beginner. Let me explain.

There are two file paths.

  • file_path - Location of default log file located.
  • file_path_myApp - Location of application log file located

Then I've defined four file types that need to be deleted. 

  • file1='catalina.2017-*';
  • file2='host-*';
  • file3='localhost*';
  • file4='manager*';

Then I get the date of yesterday because I needed to zip yesterday's log file with the date as a file name (lastLogFile).

Then I remove files using rm command in Linux. 

  • rm $file1

Then I zip the yesterday file using tar -zcvf command.

  • tar -zcvf $lastLogFile.tar.gz $lastLogFile;

Then I move files to another location using move command. 

  • mv $lastLogFile.tar.gz  /var/log/myAppLogs/

There are many file paths, you need to change all those file names with your locations. All commands are simple Linux commands. 

How to run a shell script file

Once you create your .sh file, you need to run it from the terminal.
  • Go to your file location and right-click and, open terminal in the same location( Otherwise you will need to change the path ).
  • Give file permission to the file.
                    chmod +x
  • Run your sh file.

Add a cronjob

Another special thing is you can add your script as a cronjob and it will run automatically according to the parameters which are given. For example, if you need to run it every minute, you can add the following line to system crontab.

* * * * * /media/ravi/Data/Cronjob/

Open your terminal and type crontab -e

Add your cronjob (Above mentioned line)

Save file.

  • Ctrl + X
  • Type y
  • Enter

You will be able to see this.

You can change your cronjob with your requirements. 

Maintain server logs Maintain server logs Reviewed by Ravi Yasas on 4:21 PM Rating: 5

No comments:

Powered by Blogger.