#!/bin/bash # Use logrotate to manage the logfile # # usage: ynh_use_logrotate [--logfile=/log/file] [--nonappend] [--specific_user=user/group] # | arg: -l, --logfile= - absolute path of logfile # | arg: -n, --nonappend - (optional) Replace the config file instead of appending this new config. # | arg: -u, --specific_user= - run logrotate as the specified user and group. If not specified logrotate is runned as root. # # If no `--logfile` is provided, `/var/log/$app` will be used as default. # `logfile` can point to a directory or a file. # # It's possible to use this helper multiple times, each config will be added to # the same logrotate config file. Unless you use the option `--non-append` # # Requires YunoHost version 2.6.4 or higher. # Requires YunoHost version 3.2.0 or higher for the argument `--specific_user` ynh_use_logrotate() { # Declare an array to define the options of this helper. local legacy_args=lnuya local -A args_array=([l]=logfile= [n]=nonappend [u]=specific_user= [y]=non [a]=append) # [y]=non [a]=append are only for legacy purpose, to not fail on the old option '--non-append' local logfile local nonappend local specific_user # Manage arguments with getopts ynh_handle_getopts_args "$@" logfile="${logfile:-}" nonappend="${nonappend:-0}" specific_user="${specific_user:-}" # LEGACY CODE - PRE GETOPTS if [ $# -gt 0 ] && [ "$1" == "--non-append" ]; then nonappend=1 # Destroy this argument for the next command. shift elif [ $# -gt 1 ] && [ "$2" == "--non-append" ]; then nonappend=1 fi if [ $# -gt 0 ] && [ "$(echo ${1:0:1})" != "-" ]; then # If the given logfile parameter already exists as a file, or if it ends up with ".log", # we just want to manage a single file if [ -f "$1" ] || [ "$(echo ${1##*.})" == "log" ]; then local logfile=$1 # Otherwise we assume we want to manage a directory and all its .log file inside else local logfile=$1/*.log fi fi # LEGACY CODE local customtee="tee --append" if [ "$nonappend" -eq 1 ]; then customtee="tee" fi if [ -n "$logfile" ]; then if [ ! -f "$1" ] && [ "$(echo ${logfile##*.})" != "log" ]; then # Keep only the extension to check if it's a logfile local logfile="$logfile/*.log" # Else, uses the directory and all logfile into it. fi else logfile="/var/log/${app}/*.log" # Without argument, use a defaut directory in /var/log fi local su_directive="" if [[ -n $specific_user ]]; then su_directive=" # Run logorotate as specific user - group su ${specific_user%/*} ${specific_user#*/}" fi cat >./${app}-logrotate </dev/null # Append this config to the existing config file, or replace the whole config file (depending on $customtee) } # Remove the app's logrotate config. # # usage: ynh_remove_logrotate # # Requires YunoHost version 2.6.4 or higher. ynh_remove_logrotate() { if [ -e "/etc/logrotate.d/$app" ]; then rm "/etc/logrotate.d/$app" fi }