1use strict;
2use warnings;
3
4use PostgresNode;
5use TestLib;
6use Test::More tests => 5;
7use Time::HiRes qw(usleep);
8
9# Set up node with logging collector
10my $node = get_new_node('primary');
11$node->init();
12$node->append_conf(
13	'postgresql.conf', qq(
14logging_collector = on
15# these ensure stability of test results:
16log_rotation_age = 0
17lc_messages = 'C'
18));
19
20$node->start();
21
22# Verify that log output gets to the file
23
24$node->psql('postgres', 'SELECT 1/0');
25
26# might need to retry if logging collector process is slow...
27my $max_attempts = 180 * 10;
28
29my $current_logfiles;
30for (my $attempts = 0; $attempts < $max_attempts; $attempts++)
31{
32	eval {
33		$current_logfiles = slurp_file($node->data_dir . '/current_logfiles');
34	};
35	last unless $@;
36	usleep(100_000);
37}
38die $@ if $@;
39
40note "current_logfiles = $current_logfiles";
41
42like(
43	$current_logfiles,
44	qr|^stderr log/postgresql-.*log$|,
45	'current_logfiles is sane');
46
47my $lfname = $current_logfiles;
48$lfname =~ s/^stderr //;
49chomp $lfname;
50
51my $first_logfile;
52for (my $attempts = 0; $attempts < $max_attempts; $attempts++)
53{
54	$first_logfile = slurp_file($node->data_dir . '/' . $lfname);
55	last if $first_logfile =~ m/division by zero/;
56	usleep(100_000);
57}
58
59like($first_logfile, qr/division by zero/, 'found expected log file content');
60
61# While we're at it, test pg_current_logfile() function
62is($node->safe_psql('postgres', "SELECT pg_current_logfile('stderr')"),
63	$lfname, 'pg_current_logfile() gives correct answer');
64
65# Sleep 2 seconds and ask for log rotation; this should result in
66# output into a different log file name.
67sleep(2);
68$node->logrotate();
69
70# pg_ctl logrotate doesn't wait for rotation request to be completed.
71# Allow a bit of time for it to happen.
72my $new_current_logfiles;
73for (my $attempts = 0; $attempts < $max_attempts; $attempts++)
74{
75	$new_current_logfiles = slurp_file($node->data_dir . '/current_logfiles');
76	last if $new_current_logfiles ne $current_logfiles;
77	usleep(100_000);
78}
79
80note "now current_logfiles = $new_current_logfiles";
81
82like(
83	$new_current_logfiles,
84	qr|^stderr log/postgresql-.*log$|,
85	'new current_logfiles is sane');
86
87$lfname = $new_current_logfiles;
88$lfname =~ s/^stderr //;
89chomp $lfname;
90
91# Verify that log output gets to this file, too
92
93$node->psql('postgres', 'fee fi fo fum');
94
95my $second_logfile;
96for (my $attempts = 0; $attempts < $max_attempts; $attempts++)
97{
98	$second_logfile = slurp_file($node->data_dir . '/' . $lfname);
99	last if $second_logfile =~ m/syntax error/;
100	usleep(100_000);
101}
102
103like(
104	$second_logfile,
105	qr/syntax error/,
106	'found expected log file content in new log file');
107
108$node->stop();
109