我写了一个小代码,当无法连接到 postgres 数据库时,使用 C Api 将消息发送到系统日志。
int main ( int argc, char **argv )
{
PGconn *psql;
PGresult *res;
int flag = 0;
openlog ( "postgres", LOG_NDELAY, LOG_SYSLOG );
psql = PQconnectdb("hostaddr = '127.0.0.0' port = '5432' dbname = 'RtpDb' user = 'rtp_user_99' password = 'rtp_user' connect_timeout = '10'");
if ( PQstatus(psql) != CONNECTION_OK )
{
//Send an event to syslog for DB Connection Failure
syslog (LOG_EMERG, "%s", PQerrorMessage(psql) )
}
closelog ();
PQclear(res);
PQfinish(psql);
}
Run Code Online (Sandbox Code Playgroud)
当 postgres 数据库连接失败时,即使在 openlog 中未启用 LOG_CONS 选项,消息也会打印到控制台。
Broadcast message from systemd-journald@blr09 (Tue 2017-01-03 05:24:46 EST):
postgres[40933]: could not connect to server: Network is unreachable
Is the server running on host "127.0.0.0" and accepting
TCP/IP connections on port 5432?
Message from syslogd@blr09 at Jan 3 05:24:46 ...
postgres:could not connect to server: Network is unreachable#012#011Is the server running on host "127.0.0.0" and accepting#012#011TCP/IP connections on port 5432?
Run Code Online (Sandbox Code Playgroud)
你能帮我如何避免在控制台上打印消息吗?
Nik*_*hil 11
在@alk提供的提示之后,我做了一些更多的研究,并找到了如何避免在控制台上打印消息。
Broadcast message from systemd-journald@blr09 (Tue 2017-01-03 05:24:46 EST):
postgres[40933]: could not connect to server: Network is unreachable
Is the server running on host "127.0.0.0" and accepting
TCP/IP connections on port 5432?
Message from syslogd@blr09 at Jan 3 05:24:46 ...
postgres:could not connect to server: Network is unreachable#012#011Is the server running on host "127.0.0.0" and accepting#012#011TCP/IP connections on port 5432?
Run Code Online (Sandbox Code Playgroud)
上述消息有两部分:
来自systemd-journald的广播消息 => 当发送紧急消息时,这些消息将通过journalctl打印在控制台上。要禁用这些消息,我们需要禁用 ForwardToWall,即/etc/systemd/journald.conf中的ForwardToWall=no
来自 syslogd 的消息 => 由于 /etc/rsyslog.conf 中的以下配置行,这些消息由 rsyslog 打印
*.emerg :omusrmsg:*
Run Code Online (Sandbox Code Playgroud)此选择器操作声明“紧急消息通常会发送给当前在线的所有用户,通知他们系统发生了奇怪的情况。要指定此 wall(1) 功能,请使用“:omusrmsg:*”。” 注释掉这一行。
执行上述操作后,控制台上未打印消息。由于安全威胁不允许这些操作,因此我将这些事件设为警报优先级。
syslog ( LOG_ALERT, "%s", PQerrorMessage(psql) );
Run Code Online (Sandbox Code Playgroud)
感谢@alk。