├── .gitignore ├── LICENSE ├── README.md └── src └── mpfhandler.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Overview 2 | ======== 3 | This module provides an additional log handler for Python's standard 4 | logging package (PEP 282). 5 | This handler will write log events to log file which is rotated at a 6 | certain time(day, hour, min) and multiple processes supported. 7 | 8 | 这个模块提供了一个 Python logging handler 类。它会根据配置按时间来 9 | 轮转日志文件,并且支持多线程 10 | 11 | Details 12 | ======= 13 | The ``MultProcTimedRotatingFileHandler`` class is a drop-in replacement for 14 | Python's standard log handler ``RotatingFileHandler``. This module uses file 15 | locking so that multiple processes can concurrently log to a single file without 16 | dropping or clobbering log events. This module provides a file rotation scheme 17 | like with ``RotatingFileHanler``. Extra care is taken to ensure that logs 18 | can be safely rotated before the rotation process is started. 19 | 20 | This class ratating file at an exact time, such as every day(23:59:59) or 21 | every hour(xx:59:59) and so on. 22 | 23 | If you have multiple instances of a script (or multiple scripts) all running at 24 | the same time and writing to the same log file, then *all* of the scripts should 25 | be using this class. 26 | 27 | This class require `portalocker` to deal with file locking. Please be aware 28 | that portalocker only supports Unix (posix) an NT platforms at this time, and 29 | therefore this package only supports those platforms as well. But, only tested 30 | on Linux. 31 | 32 | 基于标准的 `RotatingFileHandler` 类开发,支持多线程,多进程, 33 | 轮转方式是按照时间, 每天/每小时/每分钟 不依赖于进程的启动时间,而是根据系统时间 34 | 进行轮转. 35 | 36 | 如果有多个脚本或者实例都需要打日志到同一个文件,请一定都要用这个类 37 | `MultProcTimedRotatingFileHandler`, 因为它是基于文件锁的. 38 | 39 | 这个类使用了 `portalocker` 去处理多进程之间的文件锁,所以它只支持 *nix 跟 NT 系统, 40 | 但是我只测试了在 Linux 下面使用。 41 | 42 | 43 | Why 44 | ======== 45 | This class fork from `TimedRotatingFileHandler` and `ConcurrentLogHandler`. 46 | For `TimedRotatingFileHandler` issues: 47 | 48 | 1. thread safe but not process safe 49 | 2. rotating time is accumulate, this means it deponding the process when to start up. 50 | 51 | `ConcurrentLogHandler` is good, but it only rotating by the logfile size. 52 | 53 | 54 | 这个类其实是参考了 `TimedRotatingFileHandler`,`ConcurrentLogHandler` 这两个handler, 55 | 为什么要写这个呢?主要是上面提到的这两个都有一些小问题。 56 | 57 | `TimedRotatingFileHandler`: 58 | 59 | 1. 虽然是线程安全,但是并不支持多进程 60 | 2. 轮转的时间是依赖于进程的启动时间,所以会出现轮转点并不是常规的59s. 61 | 62 | `ConcurrentLogHandler` 如果只是实现了根据日志文件大小来轮转, 未提供按时间的. 63 | 64 | 65 | Installation 66 | ============ 67 | Use the following command to install this package: 68 | 69 | pip install mpfhandler 70 | 71 | If you are installing from source, you can use: 72 | 73 | python setup.py install 74 | 75 | Or wget the single file to your python sys.path: 76 | 77 | wget https://github.com/yorks/mpfhandler/raw/master/src/mpfhandler.py -O\ 78 | /usr/lib/python2.6/site-packages/mpfhandler.py 79 | 80 | 81 | 82 | Examples 83 | ======== 84 | 85 | Simple Example 86 | -------------- 87 | Here is a example demonstrating how to use this module directly 88 | ```python 89 | 90 | from logging import getLogger, INFO 91 | from mpfhandler import MultProcTimedRotatingFileHandler 92 | import os 93 | 94 | log = getLogger() 95 | # Use an absolute path to prevent file rotation trouble. 96 | logfile = os.path.abspath("mylogfile.log") 97 | # Rotate log every hour 98 | rotateHandler = MultProcTimedRotatingFileHandler(logfile, when='h') 99 | log.addHandler(rotateHandler) 100 | log.setLevel(INFO) 101 | 102 | log.info("Here is a very exciting log message, just for you") 103 | ``` 104 | Django Example 105 | -------------- 106 | ```python 107 | # settings.py 108 | LOGGING={ 109 | #... 110 | 'handlers':{ 111 | 'custom_mpf_rotate':{ 112 | 'level': 'DEBUG', 113 | 'class': 'mpfhandler.MultProcTimedRotatingFileHandler', 114 | 'filename': os.path.join(BASE_DIR, 'logs/custom_mptf.log'), 115 | 'when' : 'D', # day, or H for hour 116 | #'interval' : 1, # TODO 117 | #'debug' : False, # handler own log 118 | 'formatter': 'verbose' 119 | }, 120 | }, 121 | 'loggers':{ 122 | ... 123 | 'customapp': { 124 | 'handlers': ['console', 'custom_mpf_rotate'], 125 | 'level': 'DEBUG', 126 | 'propagate': False, 127 | }, 128 | #... 129 | } 130 | 131 | } 132 | 133 | # app/view.py 134 | import logging 135 | log=logging.getLogger(__name__) 136 | log.info('Here is a very exciting log message, just for you') 137 | 138 | 139 | ``` 140 | 141 | Attention 142 | ========== 143 | 1. interval, backupCount options is not working! 144 | 2. $logpath.lock is the lock file to handle multiple processes, donot delete it. 145 | 3. There is no stress-testing has been done, if it slow 146 | down for logging it might be the lock issue. 147 | 148 | 149 | 注意 150 | ========= 151 | 1. `interval`, `backupCount` 参数暂不支持,这也就是说,日志的压缩清理您需要额外处理。 152 | 2. `$logpath.lock` 这个文件请不要删除,是用来出来文件锁的。 153 | 3. 还没经过压力测试,如果担心会托慢您的程序,可能是因为文件锁引起. 154 | -------------------------------------------------------------------------------- /src/mpfhandler.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import datetime 4 | import re 5 | from random import randint 6 | from logging.handlers import BaseRotatingHandler 7 | 8 | # sibling module than handles all the ugly platform-specific details of file locking 9 | from portalocker import lock, unlock, LOCK_EX 10 | 11 | __version__ = '0.0.2' 12 | __author__ = "yorks" 13 | 14 | 15 | class MultProcTimedRotatingFileHandler(BaseRotatingHandler): 16 | """ 17 | Handler for logging to a file, rotating the log file at certain timed. 18 | 19 | """ 20 | def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, debug=False): 21 | """ 22 | * interval, backupCount is not working!!! * 23 | 24 | Just Copied from logging.handlers.TimedRotatingFileHandler 25 | 26 | # a rollover occurs. Current 'when' events supported: 27 | # S - Seconds 28 | # M - Minutes 29 | # H - Hours 30 | # D - Days 31 | # midnight - roll over at midnight 32 | # W{0-6} - roll over on a certain day; 0 - Monday 33 | # 34 | # Case of the 'when' specifier is not important; lower or upper case 35 | # will work. 36 | 37 | """ 38 | BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay) 39 | self.when = when.upper() 40 | self.backupCount = backupCount 41 | self.utc = utc 42 | self.debug = debug 43 | self.mylogfile = "%s.%08d" % ('/tmp/mptfhanldler', randint(0,99999999)) 44 | 45 | self.interval = 1 # datetime timedelta only have, days, seconds, microseconds 46 | 47 | if self.when == 'S': 48 | #self.interval = 1 # one second 49 | self.suffix = "%Y-%m-%d_%H-%M-%S" 50 | self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$" 51 | elif self.when == 'M': 52 | self.interval = 60 # one minute 53 | self.suffix = "%Y-%m-%d_%H-%M" 54 | self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$" 55 | elif self.when == 'H': 56 | self.interval = 60 * 60 # one hour 57 | self.suffix = "%Y-%m-%d_%H" 58 | self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}$" 59 | elif self.when == 'D' or self.when == 'MIDNIGHT': 60 | #self.interval = 60 * 60 * 24 # one day 61 | self.suffix = "%Y-%m-%d" 62 | self.extMatch = r"^\d{4}-\d{2}-\d{2}$" 63 | self.when = 'D' # MIDNIGHT is day, use day only 64 | elif self.when.startswith('W'): 65 | #self.interval = 60 * 60 * 24 * 7 # one week 66 | if len(self.when) != 2: 67 | raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when) 68 | if self.when[1] < '0' or self.when[1] > '6': 69 | raise ValueError("Invalid day specified for weekly rollover: %s" % self.when) 70 | self.dayOfWeek = int(self.when[1]) 71 | self.suffix = "%Y-%m-%d" 72 | self.extMatch = r"^\d{4}-\d{2}-\d{2}$" 73 | else: 74 | raise ValueError("Invalid rollover interval specified: %s" % self.when) 75 | 76 | self.extMatch = re.compile(self.extMatch) 77 | #self.interval = self.interval * interval # multiply by units requested 78 | self.interval = self.interval * 1 # interval arg is not working 79 | 80 | # lock file, contain next rollover timestamp 81 | self.stream_lock = None 82 | self.lock_file = self._getLockFile() 83 | 84 | # read from conf first for inherit the first process 85 | # if it is the first process, please remove the lock file by hand first 86 | self.nextRolloverTime = self.getNextRolloverTime() 87 | if not self.nextRolloverTime: 88 | self.nextRolloverTime = self.computerNextRolloverTime() 89 | self.saveNextRolloverTime() 90 | 91 | def _log2mylog(self, msg): 92 | time_str=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) 93 | msg=str(msg) 94 | content="%s [%s]\n"% (time_str, msg) 95 | fa = open( self.mylogfile, 'a') 96 | fa.write(content) 97 | fa.close() 98 | 99 | 100 | def _getLockFile(self): 101 | # Use 'file.lock' and not 'file.log.lock' (Only handles the normal "*.log" case.) 102 | if self.baseFilename.endswith(".log"): 103 | lock_file = self.baseFilename[:-4] 104 | else: 105 | lock_file = self.baseFilename 106 | lock_file += ".lock" 107 | return lock_file 108 | 109 | def _openLockFile(self): 110 | lock_file = self._getLockFile() 111 | self.stream_lock = open(lock_file, 'w') 112 | 113 | 114 | def computerNextRolloverTime(self): 115 | """ Work out the next rollover time. """ 116 | nextTime = None 117 | currentDateTime = datetime.datetime.now() 118 | if self.utc: 119 | currentDateTime = datetime.datetime.utcnow() 120 | 121 | 122 | if self.when == 'D' : 123 | nextDateTime = currentDateTime + datetime.timedelta(days=self.interval) 124 | nextDate = nextDateTime.date() 125 | nextTime = int( time.mktime(nextDate.timetuple()) ) 126 | elif self.when.startswith('W'): 127 | days = 0 128 | currentWeekDay = currentDateTime.weekday() 129 | if currentWeekDay == self.dayOfWeek: 130 | days = ( self.interval + 7 ) 131 | elif currentWeekDay < self.dayOfWeek: 132 | days = self.dayOfWeek - currentWeekDay 133 | else: 134 | days = 6 - currentWeekDay + self.dayOfWeek + 1 135 | nextDateTime = currentDateTime + datetime.timedelta(days=days) 136 | nextDate = nextDateTime.date() 137 | nextTime = int( time.mktime(nextDate.timetuple()) ) 138 | else: 139 | tmpNextDateTime = currentDateTime + datetime.timedelta(seconds=self.interval) 140 | nextDateTime = tmpNextDateTime.replace(microsecond=0) 141 | if self.when == 'H': 142 | nextDateTime = tmpNextDateTime.replace(minute=0, second=0, microsecond=0) 143 | elif self.when == 'M': 144 | nextDateTime = tmpNextDateTime.replace(second=0, microsecond=0) 145 | 146 | nextTime = int( time.mktime(nextDateTime.timetuple()) ) 147 | return nextTime 148 | 149 | def getNextRolloverTime(self): 150 | """ get next rollover time stamp from lock file """ 151 | try: 152 | fp = open(self.lock_file, 'r') 153 | c = fp.read() 154 | fp.close() 155 | return int(c) 156 | except: 157 | return False 158 | 159 | def saveNextRolloverTime(self): 160 | """ save the nextRolloverTimestamp to lock file 161 | 162 | this is a flag for avoid multiple processes to rotate 163 | the log file again at the same rollovertime. 164 | """ 165 | if not self.nextRolloverTime: 166 | return 0 167 | content = "%d"% self.nextRolloverTime 168 | 169 | if not self.stream_lock: 170 | self._openLockFile() 171 | lock(self.stream_lock, LOCK_EX) 172 | try: 173 | self.stream_lock.seek(0) 174 | self.stream_lock.write(content) 175 | self.stream_lock.flush() 176 | except: 177 | if self.debug:self._log2mylog('saveNextRT exception!!!') 178 | pass 179 | finally: 180 | unlock(self.stream_lock) 181 | if self.debug:self._log2mylog('saveNextRT:%s'% content) 182 | 183 | 184 | def acquire(self): 185 | """ Acquire thread and file locks. 186 | 187 | Copid from ConcurrentRotatingFileHandler 188 | """ 189 | # handle thread lock 190 | BaseRotatingHandler.acquire(self) 191 | # Issue a file lock. (This is inefficient for multiple active threads 192 | # within a single process. But if you're worried about high-performance, 193 | # you probably aren't using this log handler.) 194 | if self.stream_lock: 195 | # If stream_lock=None, then assume close() was called or something 196 | # else weird and ignore all file-level locks. 197 | if self.stream_lock.closed: 198 | # Daemonization can close all open file descriptors, see 199 | # https://bugzilla.redhat.com/show_bug.cgi?id=952929 200 | # Try opening the lock file again. Should we warn() here?!? 201 | try: 202 | self._openLockFile() 203 | except : 204 | # Don't try to open the stream lock again 205 | self.stream_lock = None 206 | return 207 | lock(self.stream_lock, LOCK_EX) 208 | # Stream will be opened as part by FileHandler.emit() 209 | 210 | def release(self): 211 | """ Release file and thread locks. 212 | """ 213 | try: 214 | if self.stream_lock and not self.stream_lock.closed: 215 | unlock(self.stream_lock) 216 | except : 217 | pass 218 | finally: 219 | # release thread lock 220 | BaseRotatingHandler.release(self) 221 | 222 | def _close_stream(self): 223 | """ Close the log file stream """ 224 | if self.stream: 225 | try: 226 | if not self.stream.closed: 227 | self.stream.flush() 228 | self.stream.close() 229 | finally: 230 | self.stream = None 231 | 232 | def _close_stream_lock(self): 233 | """ Close the lock file stream """ 234 | if self.stream_lock: 235 | try: 236 | if not self.stream_lock.closed: 237 | self.stream_lock.flush() 238 | self.stream_lock.close() 239 | finally: 240 | self.stream_lock = None 241 | 242 | 243 | 244 | def close(self): 245 | """ 246 | Close log stream and stream_lock. """ 247 | try: 248 | self._close_stream() 249 | self._close_stream_lock() 250 | finally: 251 | self.stream = None 252 | self.stream_lock = None 253 | 254 | 255 | 256 | def shouldRollover(self, record): 257 | """ 258 | Determine if rollover should occur. 259 | 260 | record is not used, as we are just comparing times, but it is needed so 261 | the method signatures are the same 262 | 263 | Copied from std lib 264 | """ 265 | t = int(time.time()) 266 | if t >= self.nextRolloverTime: 267 | return 1 268 | #print "No need to rollover: %d, %d" % (t, self.rolloverAt) 269 | return 0 270 | 271 | def doRollover(self): 272 | """ Do a rollover, 273 | 274 | 0. close stream, stream_lock file handle 275 | 1. get lock 276 | 2. mv log log.$date 277 | 3. setting up nextRolloverTime 278 | 4. relese lock 279 | """ 280 | if self.debug:self._log2mylog('do Rollover') 281 | self._close_stream() 282 | self.acquire() 283 | try: 284 | fileNextRolloverTime = self.getNextRolloverTime() 285 | if not fileNextRolloverTime: 286 | if self.debug:self._log2mylog('getNextRolloverTime False, skip rotate!') 287 | self.release() 288 | return 0 289 | # avoid other process do rollover again. 290 | if self.nextRolloverTime < fileNextRolloverTime: 291 | self.nextRolloverTime = fileNextRolloverTime 292 | if self.debug:self._log2mylog('already rotated, skip this proc to rotate!') 293 | self.release() 294 | return 0 295 | except : 296 | pass 297 | # because log is older then self.nextRolloverTime, 298 | # we need the old log rename to old filename 299 | # donot use time.time()-1, 300 | # for between last rollover and nextRolloverTime*N may have none log to record. 301 | time_tuple = time.localtime( self.nextRolloverTime - 1 ) 302 | dfn = self.baseFilename + "." + time.strftime(self.suffix, time_tuple) 303 | # rename 304 | if os.path.exists( dfn ): 305 | bakname = dfn + ".bak" 306 | while os.path.exists(bakname): 307 | bakname = "%s.%08d" % (bakname, randint(0,99999999)) 308 | try: 309 | os.rename(dfn, bakname) 310 | except: 311 | pass 312 | if os.path.exists(self.baseFilename): 313 | try: 314 | if self.debug:self._log2mylog('rename %s to %s'% (self.baseFilename, dfn)) 315 | os.rename(self.baseFilename, dfn) 316 | except: 317 | pass 318 | # set new nextRolloverTime 319 | self.nextRolloverTime = self.computerNextRolloverTime() 320 | self.saveNextRolloverTime() 321 | 322 | if not self.delay: 323 | self.stream = self._open() 324 | self.release() 325 | 326 | 327 | 328 | 329 | 330 | 331 | import logging.handlers 332 | logging.handlers.MultProcTimedRotatingFileHandler = MultProcTimedRotatingFileHandler 333 | --------------------------------------------------------------------------------