0
0
Bash Scriptingscripting~30 mins

Logging framework in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Logging Framework in Bash
📖 Scenario: You are creating a simple logging framework in a Bash script. This will help you track messages with different levels like INFO, WARNING, and ERROR in your scripts.
🎯 Goal: Build a Bash script that defines a log function to print messages with a timestamp and log level. You will also set a log level threshold to control which messages get printed.
📋 What You'll Learn
Create a variable to hold the current log level threshold.
Define a function called log that takes two arguments: log level and message.
The function should print the message only if the message's log level is equal or higher than the threshold.
Print log messages with a timestamp and the log level in uppercase.
💡 Why This Matters
🌍 Real World
Logging is essential in scripts to track what happens and find problems quickly.
💼 Career
DevOps engineers and system administrators use logging frameworks to monitor and debug automation scripts.
Progress0 / 4 steps
1
Set up log level variables
Create three variables called LOG_LEVEL_INFO, LOG_LEVEL_WARNING, and LOG_LEVEL_ERROR with values 1, 2, and 3 respectively.
Bash Scripting
Need a hint?

Use simple variable assignments like VAR=value.

2
Set the current log level threshold
Create a variable called CURRENT_LOG_LEVEL and set it to LOG_LEVEL_WARNING.
Bash Scripting
Need a hint?

Assign CURRENT_LOG_LEVEL using the existing variable LOG_LEVEL_WARNING.

3
Define the log function
Write a function called log that takes two arguments: level and message. Inside the function, check if level is greater than or equal to CURRENT_LOG_LEVEL. If yes, print the message with the current timestamp and the log level in uppercase. Use date +"%Y-%m-%d %H:%M:%S" for the timestamp.
Bash Scripting
Need a hint?

Use if to compare levels, case to get level name, and echo to print.

4
Test the logging function
Call the log function three times with these arguments:
1. LOG_LEVEL_INFO, "This is an info message"
2. LOG_LEVEL_WARNING, "This is a warning message"
3. LOG_LEVEL_ERROR, "This is an error message"
Print the output of these calls.
Bash Scripting
Need a hint?

Only messages with level WARNING and ERROR should print because the threshold is WARNING.