improve log system

This commit is contained in:
2026-02-15 17:42:42 +00:00
parent 64b197cbe5
commit 456262ca65
5 changed files with 216 additions and 52 deletions
+95 -38
View File
@@ -1,5 +1,4 @@
#!/bin/bash #!/bin/bash
# ============================================= # =============================================
# Graphical Environment Manager Script # Graphical Environment Manager Script
# Disables/enables graphical environment to save RAM # Disables/enables graphical environment to save RAM
@@ -12,9 +11,37 @@
# --- Configuration --- # --- Configuration ---
LOG_FILE="/var/log/gui_manager.log" LOG_FILE="/var/log/gui_manager.log"
MAX_LOG_SIZE_KB=1024 # 1MB
# --- Functions --- # --- Functions ---
# Função de Log (modificada para usar logger)
log() {
local message="$1"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
# Escreve no ficheiro de log
echo "$timestamp: $message" | tee -a "$LOG_FILE"
# Envia para o syslog (opcional)
logger -t "gui_manager" "$message"
}
# Função para limitar o tamanho do log
limit_log_size() {
local log_file="$1"
local max_size_kb="$2"
local max_size_bytes=$((max_size_kb * 1024))
if [ -f "$log_file" ]; then
local current_size=$(stat -c %s "$log_file" 2>/dev/null || wc -c < "$log_file" 2>/dev/null)
if [ "$current_size" -gt "$max_size_bytes" ]; then
log "Aviso: Ficheiro de log $log_file excedeu $max_size_kb KB. A truncar..."
tail -n 500 "$log_file" > "${log_file}.tmp" && mv "${log_file}.tmp" "$log_file"
log "Ficheiro de log truncado. As últimas 500 linhas foram mantidas."
fi
fi
}
# Function to check if system uses systemd # Function to check if system uses systemd
is_systemd() { is_systemd() {
[ -d /run/systemd/system ] && return 0 || return 1 [ -d /run/systemd/system ] && return 0 || return 1
@@ -42,128 +69,155 @@ get_current_target() {
if is_systemd; then if is_systemd; then
systemctl get-default systemctl get-default
else else
echo "System doesn't use systemd" log "System doesn't use systemd"
return 1
fi fi
} }
# Function to show GUI status # Function to show GUI status
show_gui_status() { show_gui_status() {
if ! is_systemd; then if ! is_systemd; then
echo "$(date): System doesn't use systemd" | tee -a "$LOG_FILE" log "System doesn't use systemd"
return 1 return 1
fi fi
current_target=$(get_current_target) current_target=$(get_current_target)
dm=$(get_display_manager) dm=$(get_display_manager)
echo "$(date): Current system target: $current_target" | tee -a "$LOG_FILE" log "Current system target: $current_target"
echo "$(date): Display Manager: $(basename "$dm")" | tee -a "$LOG_FILE" log "Display Manager: $(basename "$dm")"
if [ "$current_target" = "graphical.target" ]; then if [ "$current_target" = "graphical.target" ]; then
echo "$(date): Graphical environment is ENABLED" | tee -a "$LOG_FILE" log "Graphical environment is ENABLED"
else else
echo "$(date): Graphical environment is DISABLED" | tee -a "$LOG_FILE" log "Graphical environment is DISABLED"
fi fi
# Show memory usage # Show memory usage
echo "$(date): Memory usage:" | tee -a "$LOG_FILE" log "Memory usage:"
free -h | awk '/^Mem:/ {print " Total: " $2 ", Used: " $3 ", Free: " $4}' | tee -a "$LOG_FILE" free -h | awk '/^Mem:/ {log " Total: " $2 ", Used: " $3 ", Free: " $4}'
} }
# Function to disable graphical environment # Function to disable graphical environment
disable_gui() { disable_gui() {
if ! is_systemd; then if ! is_systemd; then
echo "$(date): Error: This system doesn't use systemd" | tee -a "$LOG_FILE" log "Error: This system doesn't use systemd"
return 1 return 1
fi fi
current_target=$(get_current_target) current_target=$(get_current_target)
if [ "$current_target" != "graphical.target" ]; then if [ "$current_target" != "graphical.target" ]; then
echo "$(date): Graphical environment is already disabled" | tee -a "$LOG_FILE" log "Graphical environment is already disabled"
return 0 return 0
fi fi
echo "$(date): Disabling graphical environment..." | tee -a "$LOG_FILE" log "Disabling graphical environment..."
# Get current display manager # Get current display manager
dm=$(get_display_manager) dm=$(get_display_manager)
if [ "$dm" = "unknown" ]; then if [ "$dm" = "unknown" ]; then
echo "$(date): Error: Could not determine display manager" | tee -a "$LOG_FILE" log "Error: Could not determine display manager"
return 1 return 1
fi fi
# Show memory usage before # Show memory usage before
echo "$(date): Memory usage before disabling GUI:" | tee -a "$LOG_FILE" log "Memory usage before disabling GUI:"
free -h | awk '/^Mem:/ {print " Total: " $2 ", Used: " $3 ", Free: " $4}' | tee -a "$LOG_FILE" free -h | awk '/^Mem:/ {log " Total: " $2 ", Used: " $3 ", Free: " $4}'
# Stop display manager # Stop display manager
echo "$(date): Stopping display manager $(basename "$dm")..." | tee -a "$LOG_FILE" log "Stopping display manager $(basename "$dm")..."
systemctl stop "$(basename "$dm")" if ! systemctl stop "$(basename "$dm")"; then
log "Error: Failed to stop display manager $(basename "$dm")"
return 1
fi
# Disable graphical target # Disable graphical target
echo "$(date): Setting default target to multi-user.target..." | tee -a "$LOG_FILE" log "Setting default target to multi-user.target..."
systemctl set-default multi-user.target if ! systemctl set-default multi-user.target; then
log "Error: Failed to set default target to multi-user.target"
return 1
fi
# Show memory usage after # Show memory usage after
echo "$(date): Memory usage after disabling GUI:" | tee -a "$LOG_FILE" log "Memory usage after disabling GUI:"
free -h | awk '/^Mem:/ {print " Total: " $2 ", Used: " $3 ", Free: " $4}' | tee -a "$LOG_FILE" free -h | awk '/^Mem:/ {log " Total: " $2 ", Used: " $3 ", Free: " $4}'
echo "$(date): Graphical environment disabled successfully" | tee -a "$LOG_FILE" log "Graphical environment disabled successfully"
return 0 return 0
} }
# Function to enable graphical environment # Function to enable graphical environment
enable_gui() { enable_gui() {
if ! is_systemd; then if ! is_systemd; then
echo "$(date): Error: This system doesn't use systemd" | tee -a "$LOG_FILE" log "Error: This system doesn't use systemd"
return 1 return 1
fi fi
current_target=$(get_current_target) current_target=$(get_current_target)
if [ "$current_target" = "graphical.target" ]; then if [ "$current_target" = "graphical.target" ]; then
echo "$(date): Graphical environment is already enabled" | tee -a "$LOG_FILE" log "Graphical environment is already enabled"
return 0 return 0
fi fi
echo "$(date): Enabling graphical environment..." | tee -a "$LOG_FILE" log "Enabling graphical environment..."
# Get current display manager # Get current display manager
dm=$(get_display_manager) dm=$(get_display_manager)
if [ "$dm" = "unknown" ]; then if [ "$dm" = "unknown" ]; then
echo "$(date): Error: Could not determine display manager" | tee -a "$LOG_FILE" log "Error: Could not determine display manager"
return 1 return 1
fi fi
# Enable graphical target # Enable graphical target
echo "$(date): Setting default target to graphical.target..." | tee -a "$LOG_FILE" log "Setting default target to graphical.target..."
systemctl set-default graphical.target if ! systemctl set-default graphical.target; then
log "Error: Failed to set default target to graphical.target"
return 1
fi
# Start display manager # Start display manager
echo "$(date): Starting display manager $(basename "$dm")..." | tee -a "$LOG_FILE" log "Starting display manager $(basename "$dm")..."
systemctl start "$(basename "$dm")" if ! systemctl start "$(basename "$dm")"; then
log "Error: Failed to start display manager $(basename "$dm")"
return 1
fi
echo "$(date): Graphical environment enabled successfully" | tee -a "$LOG_FILE" log "Graphical environment enabled successfully"
return 0 return 0
} }
# Function to format free output for logging
format_free_output() {
free -h | awk '/^Mem:/ {
log " Total: " $2 ", Used: " $3 ", Free: " $4
}'
}
# --- Main Execution --- # --- Main Execution ---
# Check if running as root
if [ "$(id -u)" -ne 0 ]; then
echo "This script must be run as root" >&2
exit 1
fi
# Create log directory if it doesn't exist # Create log directory if it doesn't exist
mkdir -p /var/log mkdir -p "$(dirname "$LOG_FILE")"
limit_log_size "$LOG_FILE" "$MAX_LOG_SIZE_KB" # Verifica o tamanho do log no início
# Log script execution start
log "Starting GUI Manager Script with action: ${1:-status}"
# Determine action based on parameters or environment variable # Determine action based on parameters or environment variable
ACTION="" ACTION=""
# Check for command line parameter # Check for command line parameter
if [ $# -gt 0 ]; then if [ $# -gt 0 ]; then
ACTION="$1" ACTION="$1"
fi fi
# Check for environment variable if no parameter provided # Check for environment variable if no parameter provided
if [ -z "$ACTION" ] && [ -n "$GUI_ACTION" ]; then if [ -z "$ACTION" ] && [ -n "$GUI_ACTION" ]; then
ACTION="$GUI_ACTION" ACTION="$GUI_ACTION"
fi fi
# Default to status if no action specified # Default to status if no action specified
if [ -z "$ACTION" ]; then if [ -z "$ACTION" ]; then
ACTION="status" ACTION="status"
@@ -173,17 +227,20 @@ fi
case "$ACTION" in case "$ACTION" in
disable) disable)
disable_gui disable_gui
exit $?
;; ;;
enable) enable)
enable_gui enable_gui
exit $?
;; ;;
status) status)
show_gui_status show_gui_status
exit $?
;; ;;
*) *)
echo "Usage: $0 [enable|disable|status]" log "Usage: $0 [enable|disable|status]"
echo "Or: GUI_ACTION=enable|disable $0" log "Or: GUI_ACTION=enable|disable $0"
echo "Invalid action: $ACTION" log "Invalid action: $ACTION"
exit 1 exit 1
;; ;;
esac esac
+29 -3
View File
@@ -8,13 +8,37 @@ LOG_FILE="/var/log/network_config.log"
UDEV_RULES_FILE="/etc/udev/rules.d/81-mac-spoof.rules" UDEV_RULES_FILE="/etc/udev/rules.d/81-mac-spoof.rules"
IFACE="eth0" IFACE="eth0"
WLAN_IFACE="wlan0" WLAN_IFACE="wlan0"
MAX_LOG_SIZE_KB=1024 # 1MB
# --- Funções Auxiliares --- # --- Funções Auxiliares ---
# Função de Log # Função de Log (modificada para usar logger)
log() { log() {
local message="$1"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S') local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "$timestamp: $1" | tee -a "$LOG_FILE"
# Escreve no ficheiro de log
echo "$timestamp: $message" | tee -a "$LOG_FILE"
# Envia para o syslog (opcional)
logger -t "network_config" "$message"
}
# Função para limitar o tamanho do log
limit_log_size() {
local log_file="$1"
local max_size_kb="$2"
local max_size_bytes=$((max_size_kb * 1024))
if [ -f "$log_file" ]; then
local current_size=$(stat -c %s "$log_file" 2>/dev/null || wc -c < "$log_file" 2>/dev/null)
if [ "$current_size" -gt "$max_size_bytes" ]; then
log "Aviso: Ficheiro de log $log_file excedeu $max_size_kb KB. A truncar..."
tail -n 500 "$log_file" > "${log_file}.tmp" && mv "${log_file}.tmp" "$log_file"
log "Ficheiro de log truncado. As últimas 500 linhas foram mantidas."
fi
fi
} }
# Função para verificar se a interface tem IP # Função para verificar se a interface tem IP
@@ -273,8 +297,9 @@ monitor_network_task() {
if force_ip_renewal "$IFACE"; then if force_ip_renewal "$IFACE"; then
log "Monitor: Renovação de IP bem-sucedida. Wi-Fi permanece ativo até confirmação." log "Monitor: Renovação de IP bem-sucedida. Wi-Fi permanece ativo até confirmação."
else else
log "Monitor: Falha ao renovar IP. Ativando Wi-Fi como fallback..." log "Monitor: Falha ao renovar IP."
if ip link show "$WLAN_IFACE" &> /dev/null && ip link show "$WLAN_IFACE" | grep -q "DOWN"; then if ip link show "$WLAN_IFACE" &> /dev/null && ip link show "$WLAN_IFACE" | grep -q "DOWN"; then
log "Ativando Wi-Fi como fallback..."
if ip link set "$WLAN_IFACE" up; then if ip link set "$WLAN_IFACE" up; then
log "Monitor: Wi-Fi ($WLAN_IFACE) ativado como fallback." log "Monitor: Wi-Fi ($WLAN_IFACE) ativado como fallback."
else else
@@ -331,6 +356,7 @@ if [ "$(id -u)" -ne 0 ]; then
fi fi
mkdir -p "$(dirname "$LOG_FILE")" mkdir -p "$(dirname "$LOG_FILE")"
limit_log_size "$LOG_FILE" "$MAX_LOG_SIZE_KB" # Verifica o tamanho do log no início
# 1. Verificar se a interface existe # 1. Verificar se a interface existe
if ! ip link show "$IFACE" &> /dev/null; then if ! ip link show "$IFACE" &> /dev/null; then
+30 -5
View File
@@ -14,12 +14,37 @@ DEFAULT_GATEWAY="${GATEWAY_ENV:-10.10.0.1}" # Use GATEWAY_ENV if provided, othe
DNS_SERVERS="8.8.8.8 8.8.4.4" DNS_SERVERS="8.8.8.8 8.8.4.4"
LOG_FILE="/var/log/set_static_ip.log" LOG_FILE="/var/log/set_static_ip.log"
NETPLAN_DIR="/etc/netplan" NETPLAN_DIR="/etc/netplan"
MAX_LOG_SIZE_KB=1024 # 1MB
# --- Functions --- # --- Funções Auxiliares ---
# Function to log messages # Função de Log (modificada para usar logger)
log() { log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE" local message="$1"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
# Escreve no ficheiro de log
echo "$timestamp: $message" | tee -a "$LOG_FILE"
# Envia para o syslog (opcional)
logger -t "set_static_ip" "$message"
}
# Função para limitar o tamanho do log
limit_log_size() {
local log_file="$1"
local max_size_kb="$2"
local max_size_bytes=$((max_size_kb * 1024))
if [ -f "$log_file" ]; then
local current_size=$(stat -c %s "$log_file" 2>/dev/null || wc -c < "$log_file" 2>/dev/null)
if [ "$current_size" -gt "$max_size_bytes" ]; then
log "Aviso: Ficheiro de log $log_file excedeu $max_size_kb KB. A truncar..."
tail -n 500 "$log_file" > "${log_file}.tmp" && mv "${log_file}.tmp" "$log_file"
log "Ficheiro de log truncado. As últimas 500 linhas foram mantidas."
fi
fi
} }
# Function to fix netplan permissions # Function to fix netplan permissions
@@ -231,8 +256,8 @@ configure_static_ip() {
local interface local interface
local dns="$DNS_SERVERS" local dns="$DNS_SERVERS"
# Create log directory if it doesn't exist mkdir -p "$(dirname "$LOG_FILE")"
mkdir -p /var/log limit_log_size "$LOG_FILE" "$MAX_LOG_SIZE_KB" # Verifica o tamanho do log no início
# Get active interface # Get active interface
if ! interface=$(get_active_interface); then if ! interface=$(get_active_interface); then
+30 -3
View File
@@ -9,6 +9,7 @@
GITHUB_REPO="https://gitea.spiralragetech.com/tiago.aica/scripts/raw/branch/main/debian" GITHUB_REPO="https://gitea.spiralragetech.com/tiago.aica/scripts/raw/branch/main/debian"
SCRIPT_DIR="/usr/local/bin" SCRIPT_DIR="/usr/local/bin"
LOG_FILE="/var/log/raspberry_setup.log" LOG_FILE="/var/log/raspberry_setup.log"
MAX_LOG_SIZE_KB=1024 # 1MB
# Colors for output # Colors for output
RED='\033[0;31m' RED='\033[0;31m'
@@ -17,9 +18,33 @@ YELLOW='\033[1;33m'
BLUE='\033[1;34m' BLUE='\033[1;34m'
NC='\033[0m' # No Color NC='\033[0m' # No Color
# Function to log messages # Função de Log (modificada para usar logger)
log() { log() {
echo -e "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE" local message="$1"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
# Escreve no ficheiro de log
echo "$timestamp: $message" | tee -a "$LOG_FILE"
# Envia para o syslog (opcional)
logger -t "raspberry_setup" "$message"
}
# Função para limitar o tamanho do log
limit_log_size() {
local log_file="$1"
local max_size_kb="$2"
local max_size_bytes=$((max_size_kb * 1024))
if [ -f "$log_file" ]; then
local current_size=$(stat -c %s "$log_file" 2>/dev/null || wc -c < "$log_file" 2>/dev/null)
if [ "$current_size" -gt "$max_size_bytes" ]; then
log "Aviso: Ficheiro de log $log_file excedeu $max_size_kb KB. A truncar..."
tail -n 500 "$log_file" > "${log_file}.tmp" && mv "${log_file}.tmp" "$log_file"
log "Ficheiro de log truncado. As últimas 500 linhas foram mantidas."
fi
fi
} }
# Function to ask for confirmation # Function to ask for confirmation
@@ -482,7 +507,9 @@ main() {
log "Starting Raspberry Pi setup..." log "Starting Raspberry Pi setup..."
# Create script directory if it doesn't exist # Create script directory if it doesn't exist
mkdir -p "$SCRIPT_DIR" mkdir -p "$(dirname "$LOG_FILE")"
limit_log_size "$LOG_FILE" "$MAX_LOG_SIZE_KB" # Verifica o tamanho do log no início
# Install dependencies # Install dependencies
install_dependencies install_dependencies
+31 -2
View File
@@ -13,10 +13,35 @@ GREEN='\033[0;32m'
YELLOW='\033[1;33m' YELLOW='\033[1;33m'
BLUE='\033[1;34m' BLUE='\033[1;34m'
NC='\033[0m' # No Color NC='\033[0m' # No Color
MAX_LOG_SIZE_KB=1024 # 1MB
# Function to log messages # Função de Log (modificada para usar logger)
log() { log() {
echo -e "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE" local message="$1"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
# Escreve no ficheiro de log
echo "$timestamp: $message" | tee -a "$LOG_FILE"
# Envia para o syslog (opcional)
logger -t "debian_upgrade" "$message"
}
# Função para limitar o tamanho do log
limit_log_size() {
local log_file="$1"
local max_size_kb="$2"
local max_size_bytes=$((max_size_kb * 1024))
if [ -f "$log_file" ]; then
local current_size=$(stat -c %s "$log_file" 2>/dev/null || wc -c < "$log_file" 2>/dev/null)
if [ "$current_size" -gt "$max_size_bytes" ]; then
log "Aviso: Ficheiro de log $log_file excedeu $max_size_kb KB. A truncar..."
tail -n 500 "$log_file" > "${log_file}.tmp" && mv "${log_file}.tmp" "$log_file"
log "Ficheiro de log truncado. As últimas 500 linhas foram mantidas."
fi
fi
} }
# Function to ask for confirmation # Function to ask for confirmation
@@ -190,6 +215,10 @@ main() {
exit 1 exit 1
fi fi
mkdir -p "$(dirname "$LOG_FILE")"
limit_log_size "$LOG_FILE" "$MAX_LOG_SIZE_KB" # Verifica o tamanho do log no início
# Check if this is a Debian system # Check if this is a Debian system
if [ ! -f /etc/debian_version ]; then if [ ! -f /etc/debian_version ]; then
log "${RED}This script is only for Debian-based systems.${NC}" log "${RED}This script is only for Debian-based systems.${NC}"