Skip to content

Commit

Permalink
enable debug logging and last_log_at tracking
Browse files Browse the repository at this point in the history
  • Loading branch information
mariusandra committed Jan 26, 2024
1 parent 8d3d6a5 commit 93ef1e6
Show file tree
Hide file tree
Showing 14 changed files with 67 additions and 7 deletions.
4 changes: 3 additions & 1 deletion backend/app/api/frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def api_frame_update(id: int):
frame = Frame.query.get_or_404(id)
fields = ['scenes', 'name', 'frame_host', 'frame_port', 'ssh_user', 'ssh_pass', 'ssh_port', 'server_host',
'server_port', 'server_api_key', 'width', 'height', 'rotate', 'color', 'interval', 'metrics_interval',
'scaling_mode', 'background_color', 'device']
'scaling_mode', 'background_color', 'device', 'debug']
defaults = {'frame_port': 8787, 'ssh_port': 22}
try:
payload = request.json
Expand All @@ -139,6 +139,8 @@ def api_frame_update(id: int):
value = int(value)
elif field in ['interval', 'metrics_interval'] and value is not None:
value = float(value)
elif field in ['debug']:
value = value == 'true' or value is True
elif field in ['scenes']:
if isinstance(value, str):
value = json.loads(value) if value is not None else None
Expand Down
4 changes: 2 additions & 2 deletions backend/app/codegen/scene_nim.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ def node_id_to_integer(node_id: str) -> int:
import frameos/channels
{newline.join(imports)}
const DEBUG = false
const DEBUG = {'true' if frame.debug else 'false'}
type Scene* = ref object of FrameScene
{(newline + " ").join(scene_object_fields)}
Expand All @@ -209,7 +209,7 @@ def node_id_to_integer(node_id: str) -> int:
else:
nextNode = -1.NodeId
if DEBUG:
self.logger.log(%*{{"event": "runApp", "node": currentNode, "ms": (-timer + epochTime()) * 1000}})
self.logger.log(%*{{"event": "scene:debug:app", "node": currentNode, "ms": (-timer + epochTime()) * 1000}})
proc runEvent*(self: Scene, context: var ExecutionContext) =
case context.event:
Expand Down
6 changes: 6 additions & 0 deletions backend/app/models/frame.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
import uuid
import secrets
from datetime import timezone
from app import db, socketio
from typing import Optional
from sqlalchemy.dialects.sqlite import JSON
Expand Down Expand Up @@ -35,6 +36,8 @@ class Frame(db.Model):
scaling_mode = db.Column(db.String(64), nullable=True) # cover (default), contain, stretch, center
background_color = db.Column(db.String(64), nullable=True)
rotate = db.Column(db.Integer, nullable=True)
debug = db.Column(db.Boolean, nullable=True)
last_log_at = db.Column(db.DateTime, nullable=True)
# apps
apps = db.Column(JSON, nullable=True)
scenes = db.Column(JSON, nullable=True)
Expand Down Expand Up @@ -65,7 +68,9 @@ def to_dict(self):
'scaling_mode': self.scaling_mode,
'rotate': self.rotate,
'background_color': self.background_color,
'debug': self.debug,
'scenes': self.scenes,
'last_log_at': self.last_log_at.replace(tzinfo=timezone.utc).isoformat() if self.last_log_at else None,
}


Expand Down Expand Up @@ -198,6 +203,7 @@ def get_frame_json(frame: Frame) -> dict:
"backgroundColor": frame.background_color or "white",
"interval": frame.interval or 30.0,
"metricsInterval": frame.metrics_interval or 60.0,
"debug": frame.debug or False,
"scalingMode": frame.scaling_mode or "cover",
"rotate": frame.rotate or 0,
}
Expand Down
3 changes: 2 additions & 1 deletion backend/app/models/log.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json
from datetime import timezone
from datetime import timezone, datetime
from copy import deepcopy
from app import db, socketio
from .frame import Frame, update_frame
Expand Down Expand Up @@ -63,6 +63,7 @@ def process_log(frame: Frame, log: dict):
if 'config' in log and key in log['config'] and log['config'][key] is not None and log['config'][key] != getattr(frame, key):
changes[key] = log['config'][key]
if len(changes) > 0:
changes['last_log_at'] = datetime.utcnow()
for key, value in changes.items():
setattr(frame, key, value)
update_frame(frame)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""frame debug and last log
Revision ID: 3145a02fc973
Revises: f4fafd71db11
Create Date: 2024-01-27 00:31:21.815386
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '3145a02fc973'
down_revision = 'f4fafd71db11'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('frame', schema=None) as batch_op:
batch_op.add_column(sa.Column('debug', sa.Boolean(), nullable=True))
batch_op.add_column(sa.Column('last_log_at', sa.DateTime(), nullable=True))

# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('frame', schema=None) as batch_op:
batch_op.drop_column('last_log_at')
batch_op.drop_column('debug')

# ### end Alembic commands ###
2 changes: 1 addition & 1 deletion frameos/src/frameos/config.nim
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ proc loadConfig*(filename: string = "frame.json"): FrameConfig =
rotate: data{"rotate"}.getInt(),
scalingMode: data{"scalingMode"}.getStr(),
settings: data{"settings"},
verbose: commandLineParams().contains("--verbose")
debug: data{"debug"}.getBool() or commandLineParams().contains("--debug")
)
setConfigDefaults(result)

Expand Down
1 change: 1 addition & 0 deletions frameos/src/frameos/frameos.nim
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ proc start*(self: FrameOS) {.async.} =
"scaling_mode": self.frameConfig.scalingMode,
"rotate": self.frameConfig.rotate,
"background_color": self.frameConfig.backgroundColor.toHtmlHex.toLowerAscii,
"debug": self.frameConfig.debug,
}}
self.logger.log(message)
self.runner.start()
Expand Down
2 changes: 1 addition & 1 deletion frameos/src/frameos/logger.nim
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ proc run(self: LoggerThread) =

let (success, payload) = logChannel.tryRecv()
if success:
if self.frameConfig.verbose:
if self.frameConfig.debug:
echo payload
self.logs.add(payload)
else:
Expand Down
1 change: 1 addition & 0 deletions frameos/src/frameos/tests/test_config.nim
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ block test_load_config:
doAssert config.interval == 300
doAssert config.metrics_interval == 60 # 60.0 in frame.json
doAssert config.rotate == 0
doAssert config.debug == false
doAssert config.scalingMode == "cover"
doAssert config.backgroundColor == "blue" # not the default
doAssert config.settings == %*{"sentry": {"frame_dsn": nil}}
Expand Down
2 changes: 1 addition & 1 deletion frameos/src/frameos/types.nim
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type
scalingMode*: string
backgroundColor*: Color
settings*: JsonNode
verbose*: bool
debug*: bool

Logger* = ref object
frameConfig*: FrameConfig
Expand Down
1 change: 1 addition & 0 deletions frontend/src/scenes/frame/frameLogic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const FRAME_KEYS = [
'rotate',
'background_color',
'scenes',
'debug',
]

export const frameLogic = kea<frameLogicType>([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ export function FrameDetails({ className }: DetailsProps) {
<td className="text-blue-200 text-right">Background color:</td>
<td className="truncate">{frame.background_color}</td>
</tr>
<tr>
<td className="text-blue-200 text-right">Debug logging:</td>
<td className="truncate">{frame.debug ? 'enabled' : 'disabled'}</td>
</tr>
<tr>
<td className="text-blue-200 text-right">Frame URL:</td>
<td className="truncate">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,15 @@ export function FrameSettings({ className }: DetailsProps) {
<Field name="background_color" label="Background color">
<TextInput type="color" name="background_color" className="!p-0" placeholder="white" />
</Field>
<Field name="debug" label="Debug logging (noisy)">
<Select
name="debug"
options={[
{ value: 'false', label: 'Disabled' },
{ value: 'true', label: 'Enabled' },
]}
/>
</Field>
</Form>
</>
)}
Expand Down
1 change: 1 addition & 0 deletions frontend/src/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export interface FrameType {
rotate?: number
background_color: string
scenes?: FrameScene[]
debug?: boolean
}

export interface TemplateType {
Expand Down

0 comments on commit 93ef1e6

Please sign in to comment.