import { AzureService, ServiceResult } from './base-service.js';
import { CacheKeys } from '../lib/cache.js';
import { executeAzCommand } from '../lib/cli-executor.js';
interface LogAnalyticsWorkspace {
name: string;
resourceGroup: string;
location: string;
customerId: string;
sku: { name: string };
}
interface LogTable {
name: string;
plan: string;
}
export class MonitorService extends AzureService {
readonly serviceName = 'Monitor';
readonly cliPrefix = 'monitor';
async list(resourceGroup?: string): Promise<ServiceResult<LogAnalyticsWorkspace[]>> {
const cacheKey = CacheKeys.service('monitor', 'workspaces', resourceGroup ?? '');
return this.cachedExecute(cacheKey, async () => {
const opts: Record<string, string> = {};
if (resourceGroup) opts['resource-group'] = resourceGroup;
const result = await this.execute('log-analytics workspace list', opts);
return this.toResult<LogAnalyticsWorkspace[]>(result);
});
}
async getWorkspace(workspaceName: string, resourceGroup: string): Promise<ServiceResult> {
const result = await this.execute('log-analytics workspace show', {
'workspace-name': workspaceName,
'resource-group': resourceGroup
});
return this.toResult(result);
}
async listTables(workspaceName: string, resourceGroup: string): Promise<ServiceResult<LogTable[]>> {
const cacheKey = CacheKeys.service('monitor', 'tables', workspaceName);
return this.cachedExecute(cacheKey, async () => {
const result = await this.execute('log-analytics workspace table list', {
'workspace-name': workspaceName,
'resource-group': resourceGroup
});
return this.toResult<LogTable[]>(result);
});
}
async queryLogs(workspaceId: string, query: string, timespan?: string): Promise<ServiceResult> {
const escapedQuery = query.replace(/"/g, '\\"');
let cmd = `az monitor log-analytics query --workspace "${workspaceId}" --analytics-query "${escapedQuery}"`;
if (timespan) cmd += ` --timespan "${timespan}"`;
const result = await executeAzCommand(cmd, { enableRetry: true });
return this.toResult(result, cmd);
}
async listMetricDefinitions(resourceId: string): Promise<ServiceResult> {
const result = await this.execute('metrics list-definitions', { 'resource': resourceId });
return this.toResult(result);
}
async getMetrics(resourceId: string, metricNames: string, interval?: string): Promise<ServiceResult> {
const opts: Record<string, string> = { 'resource': resourceId, 'metric': metricNames };
if (interval) opts['interval'] = interval;
const result = await this.execute('metrics list', opts);
return this.toResult(result);
}
}