温馨提示×

debian定时器如何做日志

小樊
39
2026-10-13 16:39:00
栏目: 智能运维

在 Debian(以及大多数 Linux 发行版)里,“定时器”通常指 systemd timer(代替 cron 的现代方式)。下面分两种常见情况说明如何做日志。


一、使用 systemd timer(推荐方式)

1. 创建 service 和 timer

service 文件 /etc/systemd/system/mytask.service

[Unit]
Description=My Task

[Service]
Type=oneshot
ExecStart=/usr/local/bin/mytask.sh

timer 文件 /etc/systemd/system/mytask.timer

[Unit]
Description=Run My Task Daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

启用:

systemctl daemon-reload
systemctl enable --now mytask.timer

2. 日志怎么看(核心)

systemd 会自动把 stdout / stderr 写入 journald:

journalctl -u mytask.service

实时查看:

journalctl -u mytask.service -f

按时间筛选:

journalctl -u mytask.service --since "2026-01-20"

✅ 不需要自己写日志文件,这是 systemd timer 最大优势。


3. 如果想要“自己的日志文件”

在脚本里重定向即可:

#!/bin/bash
echo "$(date) task start" >> /var/log/mytask.log

或者 service 里:

ExecStart=/usr/local/bin/mytask.sh >> /var/log/mytask.log 2>&1

4. 日志持久化(避免重启丢失)

默认 journal 可能只存在内存中,修改:

mkdir -p /var/log/journal
systemctl restart systemd-journald

二、如果你用的是 cron(传统方式)

1. 在 crontab 里重定向

0 2 * * * /usr/local/bin/mytask.sh >> /var/log/mytask.log 2>&1

2. 查看系统 cron 日志

Debian 默认可能没开 rsyslog:

apt install rsyslog
systemctl enable --now rsyslog

查看:

tail -f /var/log/syslog | grep CRON

三、总结建议

方式 日志位置 推荐度
systemd timer journalctl ⭐⭐⭐⭐⭐
systemd + 文件 /var/log/xxx.log ⭐⭐⭐⭐
cron 手动重定向 ⭐⭐⭐

如果你愿意,可以告诉我:

  • 用的是 systemd 还是 cron
  • 是 脚本 / 命令 / 程序

我可以帮你写一个完整可运行的示例。

0 踩