Skip to content

Commit ba13b88

Browse files
committed
Improve use of faulthandler in application.
1 parent 22bfff9 commit ba13b88

1 file changed

Lines changed: 25 additions & 3 deletions

File tree

src/mapclient/application.py

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
You should have received a copy of the GNU General Public License
1919
along with MAP Client. If not, see <http://www.gnu.org/licenses/>..
2020
"""
21+
import atexit
2122
import json
2223
import multiprocessing
2324
import os
@@ -30,6 +31,7 @@
3031
import locale
3132

3233
import logging
34+
from datetime import datetime
3335
from logging import handlers
3436
from tempfile import TemporaryDirectory
3537
from zipfile import ZipFile
@@ -65,7 +67,27 @@ def get_app_path():
6567
return os.path.dirname(os.path.abspath(__file__))
6668

6769

68-
def initialise_logger(log_path):
70+
def _cleanup_crash_log(file_handle, file_path):
71+
file_handle.close()
72+
73+
try:
74+
if os.path.getsize(file_path) == 0:
75+
os.remove(file_path)
76+
except (OSError, FileNotFoundError):
77+
pass
78+
79+
80+
def _initialise_fault_handling(log_path):
81+
pid = os.getpid()
82+
timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
83+
fault_log_path = os.path.join(os.path.dirname(log_path), f'crash_{timestamp}_{pid}.log')
84+
85+
log_file = open(fault_log_path, 'w')
86+
atexit.register(_cleanup_crash_log, file_handle=log_file, file_path=fault_log_path)
87+
faulthandler.enable(file=log_file)
88+
89+
90+
def _initialise_logger(log_path):
6991
"""
7092
Initialise logger settings and information formatting
7193
"""
@@ -94,7 +116,6 @@ def program_header():
94116

95117

96118
def _prepare_application():
97-
faulthandler.enable()
98119
# import the locale, and set the locale. This is used for
99120
# locale-aware number to string formatting
100121
locale.setlocale(locale.LC_ALL, '')
@@ -105,7 +126,8 @@ def _prepare_application():
105126

106127
info.set_applications_settings(app)
107128
log_path = get_log_location()
108-
initialise_logger(log_path)
129+
_initialise_fault_handling(log_path)
130+
_initialise_logger(log_path)
109131

110132
return app
111133

0 commit comments

Comments
 (0)