代码改变世界

qt程序在Linux环境下写入系统日志及做成服务

2024-07-17 12:05  @学无止境  阅读(40)  评论(0编辑  收藏  举报

一、将日志写入linux系统日志

1、添加头文件

#include <syslog.h>

2、写入日志

QString log="log to write";

syslog(LOG_INFO,"%s",log.toStdString().c_str());

 

二、将qt控制后程序做成linux服务

参考:https://blog.csdn.net/CLinuxF/article/details/129833008

1、在程序所在目录下创建脚本

如程序名为LogDemo,脚本名为LogDemo.sh.(名称随意)

LogDemo.sh

[root@pgg build-LogDemo-gcc9-Debug]# cat LogDemo.sh
#!/bin/sh
workdir=$(cd $(dirname $0); pwd)
export LD_LIBRARY_PATH=$workdir
cd $workdir
./LogDemo 

2、在/etc/systemd/system目录下创建服务文件(centos7)

LogDemo.service
[Unit]
Description=LogDemo Service                                              
[Service]
Type=forking
#ExecStart=/project/build-LogDemo-gcc9-Debug/LogDemo
#ExecStop=/project/build-LogDemo-gcc9-Debug/LogDemo
ExecStart=/bin/bash /project/build-LogDemo-gcc9-Debug/LogDemo.sh
ExecStop=/bin/bash /project/build-LogDemo-gcc9-Debug/LogDemo.sh
StandardOutput=syslog
StandardError=inherit
[Install]
WantedBy=multi-user.target
注:
ExecStart=/project/build-LogDemo-gcc9-Debug/LogDemo ExecStop=/project/build-LogDemo-gcc9-Debug/LogDemo
这样直接写程序名好像也行(不用脚本了);

3、启动服务

systemctl start LogDemo.service
关闭服务
systemctl stop LogDemo.service

开机启动
systemctl enable LogDemo.service

4、查看系统日志
参考:https://blog.csdn.net/Dontla/article/details/132415985
journalctl -u LogDemo -f