Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Add logs option to CLI to print / tail logs from deployed agends #192

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

theycallmeswift
Copy link

This PR adds support for a new flatfile logs command that will allow users to view and tail the logs from their deployed agents.

https://www.loom.com/share/833c08b93a0a4b78b7e8d40294d882f1?sid=fb179235-4482-4c2b-98ce-7b23357e97b4

@theycallmeswift theycallmeswift added the enhancement New feature or request label Sep 16, 2024
@theycallmeswift theycallmeswift self-assigned this Sep 16, 2024
Copy link
Contributor

coderabbitai bot commented Sep 16, 2024

Walkthrough

This update introduces a new feature that enables the retrieval of logs from deployed flatfile agents within the system. It enhances the command-line interface (CLI) by adding a logs command, allowing users to display and manage logs with various options for customization. Additionally, a new action file implements the functionality to fetch, filter, and format logs, including support for real-time log tailing. The changes improve the visibility and management of logs, facilitating better monitoring and debugging of flatfile agents.

Changes

File Change Summary
.changeset/clean-news-arrive.md Added capability to retrieve logs from deployed flatfile agents in the logging module.
packages/cli/src/index.ts Introduced logs command with options for project slug, continuous log display, authentication token, and API URL.
packages/cli/src/x/actions/logs.action.ts Added functionality to fetch and display logs from agents, including agent selection and log filtering by severity.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant API
    participant Agent

    User->>CLI: Execute logs command
    CLI->>API: Authenticate user
    API-->>CLI: Return credentials
    CLI->>API: Fetch agents
    API-->>CLI: List of agents
    CLI->>User: Prompt for agent selection
    User->>CLI: Select agent
    CLI->>API: Retrieve logs for selected agent
    API-->>CLI: Return logs
    CLI->>Agent: Filter and format logs
    Agent-->>CLI: Display logs to user
    alt Tail logs option selected
        CLI->>API: Poll for new logs
        API-->>CLI: Return new logs
        CLI->>Agent: Update displayed logs
    end
Loading

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7a8a62f and 9f9c3bb.

Files selected for processing (3)
  • .changeset/clean-news-arrive.md (1 hunks)
  • packages/cli/src/index.ts (3 hunks)
  • packages/cli/src/x/actions/logs.action.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • .changeset/clean-news-arrive.md
Additional comments not posted (5)
packages/cli/src/index.ts (1)

66-91: LGTM!

The new logs command is implemented correctly and aligns with the PR objectives. The command definition, options, and action integration are all in place.

Key points:

  • The command is defined using the program.command('logs') syntax.
  • Relevant options are added to customize the log display, such as project slug, continuous tailing, log limit, authentication token, and API URL.
  • The action method correctly specifies the logsAction function to be invoked when the command is executed.

The addition of this command enhances the CLI functionality by providing users with a convenient way to view and tail logs from deployed agents.

packages/cli/src/x/actions/logs.action.ts (4)

19-25: LGTM!

The function logic is correct, and the implementation looks good.


36-61: LGTM!

The function handles agent selection correctly, covering all possible scenarios:

  • When a slug is provided or there's no data.
  • When there are multiple agents to choose from.
  • When there is only one agent and no slug is provided.

The implementation looks good.


70-105: LGTM!

The function correctly parses and prints the logs from an array of agent logs:

  • It handles error logs by printing them with an "ERROR" prefix in red color.
  • For successful logs, it filters out empty lines and status lines, reverses the order, and extracts the relevant parts (timestamp, level, message).
  • It color-codes the log level for better readability.
  • The formatted log lines are printed with the timestamp, level, and message.

The implementation looks good and effectively handles the parsing and formatting of logs.


136-153: LGTM!

The function correctly fetches and returns the logs for an agent:

  • It calls the appropriate API method (getAgentLogs) to fetch the logs for the specified agent and environment.
  • If sinceEvent is not provided, it directly returns the fetched logs.
  • If sinceEvent is provided, it filters the logs to include only those created after the sinceEvent timestamp and excludes the log with the same event ID as sinceEvent.

The implementation looks good and effectively handles the fetching and filtering of logs based on the provided parameters.

Comment on lines +107 to +209
apiUrl: string
token: string
number: number
tail: boolean
}>
): Promise<void> {
let authRes
try {
authRes = await getAuth(options)
} catch (e) {
return program.error(messages.error(e))
}

const { apiKey, apiUrl, environment } = authRes
const slug = options?.slug || process.env.FLATFILE_AGENT_SLUG
const apiClient = apiKeyClient({ apiUrl, apiKey: apiKey! })

/**
* fetchLogs
*
* Fetchs and returns the logs for an agent. Optionally, fetch logs since a given ID.
*
* @param {Flatfile.AgentId} agentId - the ID of the agent to fetch logs for
* @param {Flatfile.EventId} sinceEventId - the ID of the event log to fetch logs since
* @returns {Promise<Flatfile.AgentLog[]>} - the logs
*/
const fetchLogs = async (
agentId: Flatfile.AgentId,
sinceEvent?: Flatfile.AgentLog
): Promise<Flatfile.AgentLog[]> => {
const { data: logs = [] } = await apiClient.agents.getAgentLogs(agentId, {
environmentId: environment.id!,
})

if (!sinceEvent) return logs

const filtered = logs.filter(
(log) =>
log.createdAt >= sinceEvent.createdAt &&
log.eventId !== sinceEvent.eventId
)

return filtered
}

try {
const agentSpinner = ora({
text: `Select agent to display logs for...`,
}).start()
const { data } = await apiClient.agents.list({
environmentId: environment.id!,
})
const selectedAgent = await handleAgentSelection(data, slug)

if (!selectedAgent) {
const errorMessage = slug
? `Agent with slug ${chalk.cyan(slug)} not found`
: 'No agents found'

agentSpinner.fail(errorMessage)
process.exit(1)
}

const agentName = selectedAgent.slug || selectedAgent.id
agentSpinner.succeed(`Selected agent: ${chalk.cyan(agentName)}`)

const logs = await fetchLogs(selectedAgent.id)
const maxLogs = options?.number || logs.length
const initialLogs = logs.slice(0, maxLogs).reverse()

// Print the intially requested logs
printLogs(initialLogs)

if (options?.tail) {
let lastEvent = initialLogs[initialLogs.length - 1]
let timer: ReturnType<typeof setTimeout>

// The logs endpoint does not support streaming responses, so we need to poll every few seconds.
const poll = async () => {
const newLogs = (await fetchLogs(selectedAgent.id, lastEvent)).reverse()

if (newLogs.length > 0) {
printLogs(newLogs)
lastEvent = newLogs[newLogs.length - 1]
}

timer = setTimeout(poll, 2500)
}

poll()

process.on('SIGINT', () => {
if (timer) clearTimeout(timer)
process.exit()
})
}
} catch (e) {
return program.error(messages.error(e))
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider refactoring the function to improve readability and maintainability.

The logsAction function is quite large and has multiple responsibilities. To improve readability and maintainability, consider the following suggestions:

  1. Extract the authentication logic into a separate function.
  2. Extract the agent selection logic into a separate function.
  3. Extract the log fetching and printing logic into separate functions.
  4. Extract the polling logic into a separate function.

By breaking down the function into smaller, focused functions, the code will become more modular and easier to understand and maintain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants