11import json
2-
2+ from datetime import datetime
33from elasticsearch import NotFoundError
44
55from django .db import router
2323from .connection import set_connection
2424
2525
26- def get_index_name (logger_name ):
27- return '{}-{}-log' .format (
26+ def get_index_name (logger_name , partitioned = True ):
27+ index_name = '{}-{}-log' .format (
2828 settings .ELASTICSEARCH_DATABASE .get ('prefix' , 'security' ),
2929 logger_name .value ,
3030 )
31+ if partitioned :
32+ index_name += '*'
33+
34+ return index_name
3135
3236
3337class JSONTextField (CustomField ):
@@ -111,7 +115,31 @@ def update(
111115 )
112116
113117
114- class RequestLog (Log ):
118+ class PartitionedLog (Log ):
119+
120+ DAY_FORMAT = "%Y-%m-%d"
121+
122+ def save (self , ** kwargs ):
123+ # assign now if no timestamp given
124+ if not self .start :
125+ self .start = datetime .now ()
126+
127+ # override the index to go to the proper timeslot
128+ kwargs ['index' ] = self ._format_index_name (self .start )
129+ return super ().save (** kwargs )
130+
131+ @classmethod
132+ def get (cls , * args , ** kwargs ):
133+ now = datetime .now ()
134+ kwargs ['index' ] = cls ._format_index_name (now )
135+ return super ().get (* args , ** kwargs )
136+
137+ @staticmethod
138+ def _format_index_name (dt ):
139+ return dt .strftime (f'{ cls ._index ._name .replace ("*" , "" )} -%Y-%m-%d' )
140+
141+
142+ class RequestLog (PartitionedLog ):
115143
116144 host = Keyword ()
117145 method = Keyword ()
@@ -152,7 +180,7 @@ class Index:
152180 name = get_index_name (LoggerName .OUTPUT_REQUEST )
153181
154182
155- class CommandLog (CommandLogStrMixin , Log ):
183+ class CommandLog (CommandLogStrMixin , PartitionedLog ):
156184
157185 name = Keyword ()
158186 input = Text ()
@@ -166,7 +194,7 @@ class Index:
166194 name = get_index_name (LoggerName .COMMAND )
167195
168196
169- class CeleryTaskInvocationLog (CeleryTaskInvocationLogStrMixin , Log ):
197+ class CeleryTaskInvocationLog (CeleryTaskInvocationLogStrMixin , PartitionedLog ):
170198
171199 celery_task_id = Keyword ()
172200 name = Keyword ()
@@ -195,7 +223,7 @@ class Index:
195223 name = get_index_name (LoggerName .CELERY_TASK_INVOCATION )
196224
197225
198- class CeleryTaskRunLog (CeleryTaskRunLogStrMixin , Log ):
226+ class CeleryTaskRunLog (CeleryTaskRunLogStrMixin , PartitionedLog ):
199227
200228 celery_task_id = Keyword ()
201229 state = EnumField (enum = CeleryTaskRunLogState )
0 commit comments