public void GetStreamWriter()
        {
            if (Directory.Exists(@"sub0"))
            {
                Directory.Delete(@"sub0", true);
            }

            var options = new LogFileFluentMigratorLoggerOptions()
            {
                OutputFileName = Path.Combine("sub0", "sub1", "abcd.log")
            };
            var streamWriter1 = LogFileAppendFluentMigratorLoggerProvider.GetStreamWriter(null, options, out var logFile);

            streamWriter1.Should().NotBeNull();
            logFile.EndsWithIgnoreCase(options.OutputFileName).Should().BeTrue($"'{logFile}' should be same as '{options.OutputFileName}'");;
            logFile.Should().EndWith(options.OutputFileName);
            for (var i = 0; i < 10; i++)
            {
                var streamWriter2 = LogFileAppendFluentMigratorLoggerProvider.GetStreamWriter(null, options, out logFile);
                streamWriter2.Should().NotBeNull();
                logFile.EndsWithIgnoreCase(options.OutputFileName).Should().Be(BaseConfig.InContainer, $"'{logFile}' should {(BaseConfig.InContainer ? "be same as" : "differ from" )} '{options.OutputFileName}'");
            }

            streamWriter1.Close();

            var streamWriter3 = LogFileAppendFluentMigratorLoggerProvider.GetStreamWriter(null, options, out logFile);

            streamWriter3.Should().NotBeNull();

            logFile.EndsWithIgnoreCase(options.OutputFileName).Should().BeTrue($"'{logFile}' should be same as '{options.OutputFileName}'");
        }
        public static ILoggingBuilder AddFluentMigratorFileLogger(
            this ILoggingBuilder loggingBuilder,
            LogFileFluentMigratorLoggerOptions options,
            bool clearProviders = false)
        {
            if (clearProviders)
            {
                loggingBuilder.ClearProviders();
            }

            var assembly = loggingBuilder.Services
                           .GetFirstServiceDescriptor <IMigrationSourceItem>()
                           .GetImplementation <IMigrationSourceItem>()
                           ?.MigrationTypeCandidates?.FirstOrDefault()?.Assembly;

            var assemblySourceItem = assembly == null
                ? new AssemblySourceItem()
                : new AssemblySourceItem(assembly);

            var optionsManager = new OptionsManager <AssemblySourceOptions>(
                new OptionsFactory <AssemblySourceOptions>(
                    Enumerable.Empty <IConfigureOptions <AssemblySourceOptions> >(),
                    Enumerable.Empty <IPostConfigureOptions <AssemblySourceOptions> >()));

            var assemblySource = new AssemblySource(optionsManager, new List <IAssemblyLoadEngine>(), new[] { assemblySourceItem });

            return(loggingBuilder.AddProvider(new LogFileFluentMigratorLoggerProvider(assemblySource, new OptionsWrapper <LogFileFluentMigratorLoggerOptions>(options))));
        }
Ejemplo n.º 3
0
        public ExtendedOracleProcessorBase(OracleBaseDbFactory factory,
                                           IMigrationGenerator generator,
                                           ILogger logger,
                                           IOptionsSnapshot <ProcessorOptions> options,
                                           IOptionsSnapshot <RunnerOptions> runnerOptions,
                                           IConnectionStringAccessor connectionStringAccessor,
                                           IExtendedMigrationGenerator <ExtendedOracleMigrationGenerator> extendedGenerator,
                                           IDbMigrationConfig migrationConfig,
                                           IMigrationSourceItem migrationSourceItem   = null,
                                           IVersionTableMetaData versionTableMetaData = null,
                                           IOptions <FluentMigratorLoggerOptions> loggerGenOptions      = null,
                                           IOptions <LogFileFluentMigratorLoggerOptions> logFileOptions = null) : base(ProcessorIds.OracleProcessorId, factory, generator, logger, options, connectionStringAccessor)
        {
            RunnerOptions        = runnerOptions;
            MigrationConfig      = migrationConfig;
            VersionTableMetaData = versionTableMetaData;
            LoggerOptions        = loggerGenOptions?.Value;
            LoggerFileOptions    = logFileOptions?.Value;

            IsSqlLogEnabled = (LoggerOptions?.ShowSql ?? false) || (LoggerFileOptions?.ShowSql ?? false);

            ExtendedGenerator = extendedGenerator;
            MigrationMetadata = new MigrationMetadata(migrationSourceItem).InitMetadata(MigrationConfig);

            ConnectionStringFunc = () => connectionStringAccessor.ConnectionString;
            Initialize();
        }
        /// <summary>
        /// Add LogFileFluentMigratorLoggerProvider if enabled by configuration
        /// </summary>
        /// <param name="loggingBuilder"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static ILoggingBuilder AddFluentMigratorFileLogger(
            this ILoggingBuilder loggingBuilder,
            IConfiguration configuration = null)
        {
            configuration = GetConfiguration(loggingBuilder, configuration);

            string disabledReason = null;

            if (configuration == null || !configuration.IsMigrationLogFileEnabledInternal(out disabledReason))
            {
                disabledReason = disabledReason ?? "by missing configuration";
                loggingBuilder.Services.RemoveLogFileFluentMigratorLoggerOptions();
                loggingBuilder.Services.RemoveFluentMigratorLogFileProviders();
                if (MigrationFileLoggingDisabledReported == false)
                {
                    MigrationFileLoggingDisabledReported = true;
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    Console.WriteLine($"Migration File logging is turned off {disabledReason}");
                    Console.ResetColor();
                }

                return(loggingBuilder);
            }

            var options = new LogFileFluentMigratorLoggerOptions
            {
                ShowSql         = configuration.IsMigrationLogFileShowSqlEnabled(),
                ShowElapsedTime = configuration.IsMigrationLogFileShowElapsedTimeEnabled(),
                OutputFileName  = configuration.GetMigrationLogFile()
            };

            return(loggingBuilder.AddFluentMigratorFileLogger(options));
        }
        /// <summary>
        /// Add LogFileFluentMigratorLoggerProvider with setting in 'options' parameter
        /// </summary>
        /// <param name="loggingBuilder"></param>
        /// <param name="options"></param>
        /// <param name="clearLoggingProviders">If true, all log-providers is first removed</param>
        /// <returns></returns>
        public static ILoggingBuilder AddFluentMigratorFileLogger(
            this ILoggingBuilder loggingBuilder,
            LogFileFluentMigratorLoggerOptions options,
            bool clearLoggingProviders = false)
        {
            if (clearLoggingProviders)
            {
                loggingBuilder.ClearProviders();
            }

            loggingBuilder.Services.AddSingleton <IOptions <LogFileFluentMigratorLoggerOptions> >(new OptionsWrapper <LogFileFluentMigratorLoggerOptions>(options));
            loggingBuilder.Services.AddSingleton <ILoggerProvider, LogFileFluentMigratorLoggerProvider>();
            return(loggingBuilder);
        }
        public static ILoggingBuilder AddFluentMigratorFileLogger(
            this ILoggingBuilder loggingBuilder,
            IConfiguration configuration = null)
        {
            configuration = GetConfiguration(loggingBuilder, configuration);

            if (configuration == null || !configuration.IsMigrationLogFileEnabled())
            {
                return(loggingBuilder);
            }

            var options = new LogFileFluentMigratorLoggerOptions
            {
                ShowSql         = configuration.IsMigrationLogShowSqlEnabled(),
                ShowElapsedTime = configuration.IsMigrationLogShowElapsedTimeEnabled(),
                OutputFileName  = configuration.GetMigrationLogFile()
            };

            return(loggingBuilder.AddFluentMigratorFileLogger(options));
        }
        /// <summary>
        /// Add LogFileFluentMigratorLoggerProvider with setting in 'options' parameter
        /// </summary>
        /// <param name="loggingBuilder"></param>
        /// <param name="options"></param>
        /// <param name="clearLoggingProviders">If true, all log-providers is first removed</param>
        /// <returns></returns>
        public static ILoggingBuilder AddFluentMigratorFileLogger(
            this ILoggingBuilder loggingBuilder,
            LogFileFluentMigratorLoggerOptions options,
            bool clearLoggingProviders = false)
        {
            if (clearLoggingProviders)
            {
                loggingBuilder.ClearProviders();
            }

            if (options == null)
            {
                var configuration = GetConfiguration(loggingBuilder, null);
                options = new LogFileFluentMigratorLoggerOptions
                {
                    ShowSql         = configuration?.IsMigrationLogFileShowSqlEnabled() ?? false,
                    ShowElapsedTime = configuration?.IsMigrationLogFileShowElapsedTimeEnabled() ?? false,
                    OutputFileName  = configuration?.GetMigrationLogFile()
                };
            }

            loggingBuilder.Services.RemoveLogFileFluentMigratorLoggerOptions();
            loggingBuilder.Services.AddSingleton <IOptions <LogFileFluentMigratorLoggerOptions> >(new OptionsWrapper <LogFileFluentMigratorLoggerOptions>(options));
            if (UseLogFileAppendFluentMigratorLoggerProvider)
            {
                loggingBuilder.Services.AddLogFileAppendFluentMigratorLoggerProvider();
            }
            else
            {
                if (options.OutputFileName != null)
                {
                    var writer = LogFileAppendFluentMigratorLoggerProvider.GetStreamWriter(null, options, out var logFile);
                    writer?.Close();

                    options.OutputFileName = logFile;
                }

                loggingBuilder.Services.AddLogFileFluentMigratorLoggerProvider();
            }
            return(loggingBuilder);
        }
Ejemplo n.º 8
0
        internal static StreamWriter GetStreamWriter(IAssemblySource assemblySource, LogFileFluentMigratorLoggerOptions options, out string logFilename)
        {
            const int retryInitStreamWriter = 2;

            for (var i = 0; i < 10; i++)
            {
                // ReSharper disable once StringLiteralTypo
                var postfix = i == 0 ? null : $"{DateTime.Now:HHmmss}";
                logFilename = GetOutputFileName(assemblySource, options, postfix);
                if (GetStreamWriterLocal(logFilename, out var streamWriter))
                {
                    return(streamWriter);
                }
            }

            logFilename = GetOutputFileName(assemblySource, options, new Random().Next(100000, 999999).ToString());
            return(new StreamWriter(logFilename, true, Encoding.UTF8));

            bool GetStreamWriterLocal(string logFile, out StreamWriter streamWriter)
            {
                streamWriter = null;
                for (var retries = 0; retries < retryInitStreamWriter; retries++)
                {
                    try
                    {
                        streamWriter = new StreamWriter(logFile, true, Encoding.UTF8);
                        return(true);
                    }
                    catch (Exception)
                    {
                        Task.Delay(TimeSpan.FromMilliseconds(250)).Wait();
                    }
                }

                return(false);
            }
        }
Ejemplo n.º 9
0
        internal static string GetOutputFileName(
            IAssemblySource assemblySource,
            LogFileFluentMigratorLoggerOptions options,
            string postfix = null)
        {
            string logFile = null;

            if (!string.IsNullOrEmpty(options.OutputFileName))
            {
                logFile = options.OutputFileName;
            }

            if (logFile == null && assemblySource?.Assemblies.Count == 0)
            {
                logFile = "FluentMigratorSql.log";
            }

            if (logFile == null)
            {
                var assembly = assemblySource?.Assemblies.First();
                logFile = (assembly?.Location ?? "FluentMigrator") + ".sql";
            }

            var info = new FileInfo(logFile);

            if (info.DirectoryName != null)
            {
                var directoryInfo = new DirectoryInfo(info.DirectoryName);
                var subs          = new List <string>();
                while (directoryInfo != null && directoryInfo.Exists == false)
                {
                    subs.Add(directoryInfo.Name);
                    directoryInfo = directoryInfo.Parent;
                }

                if (subs.Any())
                {
                    subs.Reverse();
                    subs.Aggregate(directoryInfo, (current, sub) => current?.CreateSubdirectory(sub));
                }
            }

            if (info.Exists == false)
            {
                return(logFile);
            }

            if (postfix == null)
            {
                return(logFile);
            }


            if (info.DirectoryName != null && Directory.GetCurrentDirectory().EqualsIgnoreCase(info.DirectoryName) == false)
            {
                logFile = Path.Combine(info.DirectoryName, $"{info.Name.SubstringTo(".")}-{postfix}{info.Extension}");
            }
            else
            {
                logFile = Path.Combine($"{info.Name.SubstringTo(".")}-{postfix}{info.Extension}");
            }


            return(logFile);
        }