# Buggy code
def _open_log_file(filename):
    """
    Helper to open the log file (always in the log dir) and cache its
    handle.  Will create a new file in the log dir if one didn't
    exist.
    """
    # we delay import of settings to keep logger module as free
    # from django as possible.
    global _LOG_FILE_HANDLES, _LOGDIR, _LOG_ROTATE_SIZE
    if not _LOGDIR:
        from django.conf import settings

        _LOGDIR = settings.LOG_DIR
        _LOG_ROTATE_SIZE = settings.CHANNEL_LOG_ROTATE_SIZE

    filename = os.path.join(_LOGDIR, filename)
    if filename in _LOG_FILE_HANDLES:
        # cache the handle
        return _LOG_FILE_HANDLES[filename]
    else:
        try:
            filehandle = EvenniaLogFile.fromFullPath(
                filename, rotateLength=_LOG_ROTATE_SIZE
            )
            # filehandle = open(filename, "a+")  # append mode + reading
            _LOG_FILE_HANDLES[filename] = filehandle
            return filehandle
        except IOError:
            log_trace()
    return None


# Traceback (exceptions.KeyError)
2017-04-14T10:08:52-0400 [AMPProtocol,0,127.0.0.1] Unhandled Error
Traceback (most recent call last):
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/python/log.py", line 101, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/python/log.py", line 84, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/python/context.py", line 81, in callWithContext
return func(*args,**kw)
--- <exception caught here> ---
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/posixbase.py", line 597, in _doReadOrWrite
why = selectable.doRead()
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/tcp.py", line 208, in doRead
return self._dataReceived(data)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/tcp.py", line 214, in _dataReceived
rval = self.protocol.dataReceived(data)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/protocols/amp.py", line 2411, in dataReceived
return Int16StringReceiver.dataReceived(self, data)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/protocols/basic.py", line 765, in dataReceived
self.stringReceived(packet)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/protocols/basic.py", line 877, in stringReceived
self.state = statehandler(string)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/protocols/amp.py", line 2464, in proto_key
self.boxReceiver.ampBoxReceived(self._currentBox)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/protocols/amp.py", line 1063, in ampBoxReceived
self._answerReceived(box)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/protocols/amp.py", line 989, in _answerReceived
question = self._outstandingRequests.pop(box[ANSWER])
exceptions.KeyError: '3433'

2017-04-14T10:08:53-0400 [evennia.server.amp.AmpServerFactory] Unhandled Error
Traceback (most recent call last):
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/python/log.py", line 84, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/python/context.py", line 81, in callWithContext
return func(*args,**kw)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/posixbase.py", line 597, in _doReadOrWrite
why = selectable.doRead()
--- <exception caught here> ---
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/tcp.py", line 1072, in doRead
transport = self.transport(skt, protocol, addr, self, s, self.reactor)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/tcp.py", line 789, in __init__
self.startReading()
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/abstract.py", line 434, in startReading
self.reactor.addReader(self)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/epollreactor.py", line 271, in addReader
EPOLLIN, EPOLLOUT)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/epollreactor.py", line 255, in _add
self._poller.modify(fd, flags)
exceptions.IOError: [Errno 2] No such file or directory

2017-04-14T10:08:54-0400 [evennia.server.amp.AmpServerFactory] Unhandled Error
Traceback (most recent call last):
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/python/log.py", line 84, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/python/context.py", line 81, in callWithContext
return func(*args,**kw)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/posixbase.py", line 597, in _doReadOrWrite
why = selectable.doRead()
--- <exception caught here> ---
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/tcp.py", line 1072, in doRead
transport = self.transport(skt, protocol, addr, self, s, self.reactor)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/tcp.py", line 789, in __init__
self.startReading()
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/abstract.py", line 434, in startReading
self.reactor.addReader(self)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/epollreactor.py", line 271, in addReader
EPOLLIN, EPOLLOUT)
File "/home/tehom/arx/local/lib/python2.7/site-packages/twisted/internet/epollreactor.py", line 255, in _add
self._poller.modify(fd, flags)
exceptions.IOError: [Errno 2] No such file or directory

# Fixed code
def _open_log_file(filename):
    """
    Helper to open the log file (always in the log dir) and cache its
    handle.  Will create a new file in the log dir if one didn't
    exist.

    To avoid keeping the filehandle open indefinitely we reset it every
    _LOG_FILE_HANDLE_RESET accesses. This may help resolve issues for very
    long uptimes and heavy log use.

    """
    # we delay import of settings to keep logger module as free
    # from django as possible.
    global _LOG_FILE_HANDLES, _LOG_FILE_HANDLE_COUNTS, _LOGDIR, _LOG_ROTATE_SIZE
    if not _LOGDIR:
        from django.conf import settings

        _LOGDIR = settings.LOG_DIR
        _LOG_ROTATE_SIZE = settings.CHANNEL_LOG_ROTATE_SIZE

    filename = os.path.join(_LOGDIR, filename)
    if filename in _LOG_FILE_HANDLES:
        _LOG_FILE_HANDLE_COUNTS[filename] += 1
        if _LOG_FILE_HANDLE_COUNTS[filename] > _LOG_FILE_HANDLE_RESET:
            # close/refresh handle
            _LOG_FILE_HANDLES[filename].close()
            del _LOG_FILE_HANDLES[filename]
        else:
            # return cached handle
            return _LOG_FILE_HANDLES[filename]
    try:
        filehandle = EvenniaLogFile.fromFullPath(
            filename, rotateLength=_LOG_ROTATE_SIZE
        )
        # filehandle = open(filename, "a+")  # append mode + reading
        _LOG_FILE_HANDLES[filename] = filehandle
        _LOG_FILE_HANDLE_COUNTS[filename] = 0
        return filehandle
    except IOError:
        log_trace()
    return None